NumPy在数组操作上的效率优于纯 Python代码吗?

看书说np的数组操作性能比python上的操作性能好,测试了一下,发现不对,是不是我错了?求拍砖。

import datetime
import numpy as np


def numpysum(n):
    a = np.arange(n) ** 2
    b = np.arange(n) ** 3
    c = a + b
    return a, b, c


def pythonsum(n):
    a = list(range(n))
    b = list(range(n))
    c = []
    for i in range(len(a)):
        a[i] = i ** 2
        b[i] = i ** 3
        c.append(a[i] + b[i])
    return a, b, c


def main():
    start = datetime.datetime.now()
    s1 = numpysum(10)
    print(s1)
    print((datetime.datetime.now() - start).microseconds)
    start = datetime.datetime.now()

    s2 = pythonsum(10)
    print(s2)
    print((datetime.datetime.now() - start).microseconds)


if __name__ == '__main__':
    main()

输出

Python 3.5.3 (default, Sep 27 2018, 17:25:39) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.6.1 -- An enhanced Interactive Python. Type '?' for help.
PyDev console: using IPython 7.6.1
Python 3.5.3 (default, Sep 27 2018, 17:25:39) 
[GCC 6.3.0 20170516] on linux
runfile('/home/livingbody/PycharmProjects/knn00/numpy/numpy00.py', wdir='/home/livingbody/PycharmProjects/knn00/numpy')
(array([ 0,  1,  4,  9, 16, 25, 36, 49, 64, 81]), array([  0,   1,   8,  27,  64, 125, 216, 343, 512, 729]), array([  0,   2,  12,  36,  80, 150, 252, 392, 576, 810]))
663
([0, 1, 4, 9, 16, 25, 36, 49, 64, 81], [0, 1, 8, 27, 64, 125, 216, 343, 512, 729], [0, 2, 12, 36, 80, 150, 252, 392, 576, 810])
22

如上所示:numpy 663ms,普通的22ms,什么情况?

发布了52 篇原创文章 · 获赞 19 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/livingbody/article/details/95452672