python - 如何提高数组大小 9e3 的列表理解速度?

标签 python performance list list-comprehension

我将数组 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]

最佳答案

有两件事可以给你带来健康的加速:

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

关于python - 如何提高数组大小 9e3 的列表理解速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49794144/

相关文章:

Python Sympy 复数的角度?

python - 作为 DataFrame 列的 Scipy 稀疏矩阵

ios - 使用多个 CALayer 蒙版时的性能问题

c++ - 返回私有(private)类成员是否比使用结构并直接访问该变量慢?

python - 检查封闭的元组

python - 如何通过可变字符数扩展固定长度的 Python 列表?

python - 更多 pythonic 方法来做到这一点(字符串拆分)?

java - Netty 性能

python - 将函数输出放入 Python 列表

java - 如何存储返回列表以便我可以在另一个类中使用它?