列表与Numpy阵列计算速度:循环
我想知道,将python中的列表附加到列表中比填充“空” numpy阵列更快或更慢。我知道Numpy直接写在C中,因此我希望它比Python的功能中的构建要快。我写了一个代码,看看是否确实如此。但是,我发现填充列表的速度比NP阵列快。我测试了此代码的较大N,以便能够忽略Numpy库中加载的效果。有人知道为什么是这种情况吗?谢谢!
代码:
import time
import numpy as np
import matplotlib.pyplot as plt
n = 10000000
t_np_0= time.perf_counter()
f = np.empty(n)
for i in range(n):
f[i] = i
t_np_1 = time.perf_counter()
print("Time elapsed numpy: ", t_np_1 - t_np_0)
t_list_0= time.perf_counter()
f = []
for i in range(n):
f.append(i)
t_list_1 = time.perf_counter()
print("Time elapsed list: ", t_list_1 - t_list_0)
speed = (t_np_1 - t_np_0)/(t_list_1 - t_list_0)
print("np is " + str((speed - 1)*100) + "% slower than list")
I was wondering if appending to a list in python would be faster or slower than filling up an 'empty' numpy array. I know that numpy is written directly in C and therefore I expect it to be faster than build in functions in python. I wrote a code to see if this was indeed the case. What I found, however, is that a filling up a list is faster than a np array. I tested this code for larger n as to be able to neglect the effect of loading in the numpy library. Does anyone know why this is the case? Thanks!
code:
import time
import numpy as np
import matplotlib.pyplot as plt
n = 10000000
t_np_0= time.perf_counter()
f = np.empty(n)
for i in range(n):
f[i] = i
t_np_1 = time.perf_counter()
print("Time elapsed numpy: ", t_np_1 - t_np_0)
t_list_0= time.perf_counter()
f = []
for i in range(n):
f.append(i)
t_list_1 = time.perf_counter()
print("Time elapsed list: ", t_list_1 - t_list_0)
speed = (t_np_1 - t_np_0)/(t_list_1 - t_list_0)
print("np is " + str((speed - 1)*100) + "% slower than list")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您使用的是列表和填充方法的附加方法。
但是,您也可以使用填充方法进行列表。
最快的方法就是这样:
其次,使用numpy对于列表(数组)创建的速度较慢,因为它使用了外部Python库,Numpy。
但是,如果要使用为任何计算创建的列表,使用Numpy可能会更快。
First, you are using appending method for list and filling method for NumPy array.
However, you can also use filling method for list.
The fastest method would be like this:
Second, using NumPy would be slower for the list (array) creation because it uses the external python library, NumPy.
However, if you want to use the list you created for any calculation, using NumPy may be faster.