【发布时间】:2018-08-18 02:45:41
【问题描述】:
我正在尝试比较 python 列表和 numpy 数组的处理时间。 我知道 numpy 数组比 python 列表快,但是当我实际检查时,我得到列表比 numpy 数组快。
这是我的代码:
import numpy
from datetime import datetime
def pythonsum(n):
'''
This function calculates the sum of two python list
'''
a = list(range(n))
b = list(range(n))
c = []
total = 0
for i in range(len(a)):
a[i] = i ** 2
b[i] = i ** 3
c.append(a[i] + b[i])
return c
def numpysum(n):
'''
This function calculates the sum of two numpy array
'''
a = numpy.arange(n) ** 2
b = numpy.arange(n) ** 3
c = a + b
return c
if __name__ == "__main__":
n = int(input("enter the range"))
start = datetime.now()
result = pythonsum(n)
delta = datetime.now()-start
print("time required by pythonsum is",delta.microseconds)
start = datetime.now()
result1 = numpysum(n)
delta = datetime.now()-start
print("time required by numpysum is",delta.microseconds)
delta = datetime.now()-start
print("time required by numpysum is",delta.microseconds)
输出:
In [32]: run numpy_practice.py
enter the range7
time required by pythonsum is 0
time required by numpysum is 1001
【问题讨论】:
-
如果您将范围扩大到... 10000000,会发生什么?
-
如果你想为函数、脚本或其他东西计时,你想使用
timeit。见this thread。 -
嗨大卫,请看输出:在 [55] 中:运行 numpy_practice.py 输入范围 10000000 pythonsum 所需的时间为 766959 numpysum 所需的时间为 123327 在 [56] 中:运行 numpy_practice.py 输入pythonsum所需的range5时间为0 numpysum所需的时间为0 在[57]中:运行numpy_practice.py输入range4000 pythonsum所需的时间为4812 numpysum所需的时间为0 在[58]中:运行numpy_practice.py输入range40时间pythonsum所需时间为0 numpysum所需时间为496
-
你能检查一下上次运行,当我进入40范围时,pythonsum消耗的时间是0,而numpysum是496。它表明numpysum比pythonsum慢。无法理解背后的原因。
-
我会指出,在某些情况下列表更快,通常是如果您的数据是非数字的(例如stackoverflow.com/questions/49112552/…)