【问题标题】:How to improve speed of list comprehension with array size 9e3?如何提高数组大小为 9e3 的列表理解速度?
【发布时间】:2018-09-22 11:09:02
【问题描述】:

我将一个数组 Amp 与另一个 B**w 相乘,其中 W 是另一个数组,然后将每个 w 的结果数组相加。

Amp 和 B 的大小为 (4867206,1),W 的大小为 (40x10^3,1)。

如果 W 的大小为 (1000,1),则当前需要 2 分 49 秒。使用大小为 40x10^3 的完整 W 时如何提高此速度?

Hw2=[np.einsum('i,i->', Amp, (np.array(B)**w)) for w in W]

【问题讨论】:

  • 你想要的输出的形状是什么? (1000, 4867206)?
  • 试试Amp.squeeze() + B.squeeze() ** w
  • dtype 是什么W
  • 所需的输出形状与 W (40e3,1) 的大小相同。
  • W 是 float64 类型。如果它会提高速度,很高兴改变。内存不是问题。

标签: python performance list list-comprehension


【解决方案1】:

有两件事可以让您获得健康的加速:

1) 您不希望在列表组合中出现array 工厂。它实际上很慢。

2) 计算log(B),然后使用exp 而不是**。这节省了很多

>>> Amp = np.random.random(4867206)
>>> B = np.random.random(4867206)
>>> W = 10 * np.random.random(40000) + 1
>>> 
>>> from time import perf_counter
>>> 
>>> t = perf_counter(); logB = np.log(B); s = perf_counter()
>>> s-t
0.1715415450744331
>>> 
>>> t = perf_counter(); [np.einsum('i,i->', Amp, B**w) for w in W[:40]]; s = perf_counter()
[232552.87174648093, 307130.7390907966, 411262.86511309125, 361323.4099230686, 254219.3700454278, 291692.2455839877, 324589.6747811661, 762459.3664474463, 224831.38520298406, 501641.86340860004, 466934.72400738456, 441544.52557156974, 995259.4253344169, 207811.00874071234, 408355.53573396447, 269901.94895861426, 304678.5850806002, 208719.98547583033, 318300.7763362345, 271688.90632957884, 388056.3735974982, 362437.1587603325, 456415.8506358219, 567634.1566253774, 418715.1493866043, 698332.545166694, 711861.6705545874, 391412.016841215, 569291.0132128834, 331811.20195587486, 898976.2873925611, 230896.99034275368, 225609.32356150646, 220438.15228011008, 526091.9360881918, 388536.063436256, 297158.4095318841, 382482.6531720307, 234679.1485575674, 263925.33778147714]
>>> s-t
15.207583270967007
>>> 
>>> t = perf_counter(); [np.einsum('i,i->', Amp, np.exp(w * logB)) for w in W[:40]]; s = perf_counter()
[232552.87174648093, 307130.7390907966, 411262.8651130912, 361323.4099230686, 254219.3700454278, 291692.2455839877, 324589.6747811661, 762459.3664474462, 224831.38520298406, 501641.86340860004, 466934.72400738456, 441544.52557156974, 995259.4253344169, 207811.00874071234, 408355.5357339644, 269901.9489586143, 304678.5850806002, 208719.98547583033, 318300.7763362345, 271688.90632957884, 388056.3735974982, 362437.1587603325, 456415.8506358219, 567634.1566253774, 418715.1493866043, 698332.545166694, 711861.6705545874, 391412.016841215, 569291.0132128834, 331811.20195587486, 898976.2873925611, 230896.99034275368, 225609.32356150646, 220438.15228011008, 526091.9360881918, 388536.063436256, 297158.4095318842, 382482.6531720308, 234679.1485575674, 263925.33778147714]
>>> s-t
5.111462005996145

【讨论】:

  • 谢谢保罗!现在它的运行速度提高了 3 倍。
  • 在我继续并行处理之前,还有其他改进吗?
  • @HarryWay 想不出来。
猜你喜欢
  • 2021-07-13
  • 2014-04-09
  • 2019-07-06
  • 2015-09-30
  • 2016-02-03
  • 2020-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多