Python数据分析学习(一):Numpy与纯Python计算向量加法速度比较

import sys
from datetime import datetime
import numpy as np


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

    return 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 c


size = int(sys.argv[1])

start = datetime.now()
c = pythonsum(size)
delta = datetime.now() - start
print("The last 2 elements of the sum", c[-2:])
print("PythonSum elapsed time in microseconds ", delta.microseconds)

start = datetime.now()
c = numpysum(size)
delta = datetime.now() - start
print("The last 2 elements of the sum", c[-2:])
print("NumPySum elapsed time in microseconds ", delta.microseconds)

运行结果: 

python vectorsum.py 100000
The last 2 elements of the sum [999950000799996, 999980000100000]
PythonSum elapsed time in microseconds  91446
The last 2 elements of the sum [999950000799996 999980000100000]
NumPySum elapsed time in microseconds  2824


python vectorsum.py 200000
The last 2 elements of the sum [7999800001599996, 7999920000200000]
PythonSum elapsed time in microseconds  178237
The last 2 elements of the sum [7999800001599996 7999920000200000]
NumPySum elapsed time in microseconds  6453


python vectorsum.py 300000
The last 2 elements of the sum [26999550002399996, 26999820000300000]
PythonSum elapsed time in microseconds 264677
The last 2 elements of the sum [26999550002399996 26999820000300000]
NumPySum elapsed time in microseconds 9951

 

 

posted @ 2018-02-28 14:31  下了一场大雨  阅读(2332)  评论(0编辑  收藏  举报