NumPyの配列操作の効率は純粋なPythonコードより優れていますか?

1604 ワード

本を読んで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 663 ms、普通の22 ms、どんな状況ですか?