简体   繁体   English

numpy数组处理比列表处理python需要更多时间

[英]numpy array processing takes more time than list processing python

I am trying to compare the processing time for python list and numpy array. 我正在尝试比较python列表和numpy数组的处理时间。 I know the fact that numpy arrays are faster than the python list but when I am checking practically I get lists are faster than numpy array. 我知道numpy数组比python列表快的事实,但是当我实际检查时,我得到的列表比numpy数组快。

Here is my code : 这是我的代码:

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)

Output : 输出:

In [32]: run numpy_practice.py
enter the range7
time required by pythonsum is 0
time required by numpysum is 1001

Change the code bellow the boiler plate to this and use the timeit module instead. 将样板下面的代码更改为此,然后使用timeit模块。 This code allows me to execute the functions a number of times and return the mean ans standard deviation execution time. 此代码使我可以多次执行函数,并返回平均和标准偏差执行时间。

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)))

By testing with n = 100, it is clear that numpy is much faster 通过用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM