Python numpy`std的时间性能不一致`
我有一些Python代码,其中包括在Python numpy`std的时间性能不一致`,python,arrays,numpy,vectorization,Python,Arrays,Numpy,Vectorization,我有一些Python代码,其中包括在numpy数组的轴上取标准偏差。通常,我的数组的维数约为[100500,2]。我发现,在我的代码中,如果我尝试在0th轴上取标准偏差,代码执行得非常慢。i、 e.如果我做了以下事情: # -------------------------------------------------------------- t1 = time.time() # Perform standard deviation using numpy function std_ou
numpy
数组的轴上取标准偏差。通常,我的数组的维数约为[100500,2]
。我发现,在我的代码中,如果我尝试在0
th轴上取标准偏差,代码执行得非常慢。i、 e.如果我做了以下事情:
# --------------------------------------------------------------
t1 = time.time()
# Perform standard deviation using numpy function
std_out = np.std(my_array, axis=0, ddof=1)
t2 = time.time()
print(t2-t1)
# --------------------------------------------------------------
我得到大约0.0034
到0.0058
秒的输出。但是,如果我分别运行2
nd轴,如下所示:
# --------------------------------------------------------------
t1 = time.time()
# Initialize empty array
std_out2 = np.zeros(my_array.shape[-2:])
# Perform standard deviation using numpy function on each of the last axis seperately
std_out2[...,0] = np.std(my_array[...,0], axis=0, ddof=1)
std_out2[...,1] = np.std(my_array[...,1], axis=0, ddof=1)
t2 = time.time()
print(t2-t1)
# --------------------------------------------------------------
我得到大约0.00076
秒的输出。我已经检查过,std_out
和std_out 2
是相等的,并且具有相同的数据类型(np.float64
)。我不明白为什么会这样
更奇怪的是,当我试图生成一个小的工作示例,以便我可以就堆栈溢出提出这个问题时,上述两种方法在时间上表现相同。换句话说,我只在代码嵌入到其他代码中时才观察到时间差。即使我使用上面给出的代码一个接一个地直接运行上述方法,也会发生这种情况
我不知道为什么会发生这种情况,我也不知道从哪里开始减少这种糟糕的时间性能。有人知道为什么会这样吗?它可能是由某种形式的内存问题引起的吗?请注意,
time.time()
不是用来衡量性能的。你应该使用ipython中的模块timeit
或%timeit
魔法。啊,好的,谢谢你-我以前没有意识到这一点!