[英]numpy array processing takes more time than list processing python
我正在嘗試比較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
將樣板下面的代碼更改為此,然后使用timeit
模塊。 此代碼使我可以多次執行函數,並返回平均和標准偏差執行時間。
if __name__ == "__main__":
import timeit
n = int(input("enter the range"))
setup = """\
import numpy as np
from __main__ import numpysum,pythonsum
n = {iterations}
""".format(iterations=n)
npex = numpy.array(timeit.repeat('numpysum(n)',setup=setup,repeat=100,number=1000))
pyex = numpy.array(timeit.repeat('pythonsum(n)',setup=setup,repeat=100,number=1000))
print("Numpy Execution Time, mean={m},std={sd}".format(m=npex.mean(),sd=npex.std(0)))
print("Python Execution Time, mean={m},std={sd}".format(m=pyex.mean(), sd=pyex.std(0)))
通過用n = 100進行測試,很明顯numpy更快
enter the range100
Numpy Execution Time, mean=0.00482892623162404,std=0.0005752600215192671
Python Execution Time, mean=0.1037349765653833,std=0.004933817536363718
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.