【发布时间】:2016-06-25 06:43:53
【问题描述】:
我正在执行类似以下代码的操作,但我对 np.roll() 函数的性能不满意。我将 baseArray 和 otherArray 相加,其中 baseArray 在每次迭代中滚动一个元素。但是当我滚动它时我不需要 baseArray 的副本,我更喜欢这样的视图,例如,当我将 baseArray 与其他数组相加时,如果 baseArray 滚动两次,那么 basearray 的第 2 个元素与第 0 个元素相加otherArray,baseArray 的第 3 个元素与 otherArray 的第一个元素等相加。
I.E.达到与 np.roll() 相同的结果,但不复制数组。
import numpy as np
from numpy import random
import cProfile
def profile():
baseArray = np.zeros(1000000)
for i in range(1000):
baseArray= np.roll(baseArray,1)
otherArray= np.random.rand(1000000)
baseArray=baseArray+otherArray
cProfile.run('profile()')
输出(注意第 3 行 - 滚动功能):
9005 function calls in 26.741 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 5.123 5.123 26.740 26.740 <ipython-input-101-9006a6c0d2e3>:5(profile)
1 0.001 0.001 26.741 26.741 <string>:1(<module>)
1000 0.237 0.000 8.966 0.009 numeric.py:1327(roll)
1000 0.004 0.000 0.005 0.000 numeric.py:476(asanyarray)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1000 12.650 0.013 12.650 0.013 {method 'rand' of 'mtrand.RandomState' objects}
1000 0.005 0.000 0.005 0.000 {method 'reshape' of 'numpy.ndarray' objects}
1000 6.390 0.006 6.390 0.006 {method 'take' of 'numpy.ndarray' objects}
2000 1.345 0.001 1.345 0.001 {numpy.core.multiarray.arange}
1000 0.001 0.000 0.001 0.000 {numpy.core.multiarray.array}
1000 0.985 0.001 0.985 0.001 {numpy.core.multiarray.concatenate}
1 0.000 0.000 0.000 0.000 {numpy.core.multiarray.zeros}
1 0.000 0.000 0.000 0.000 {range}
【问题讨论】:
标签: python performance numpy