原生python与numpy数组向量相加效率对比
计算一个数据元素的平方与立方之和
1、原生python
#向量相加 - 原生Python def pythonvector(n): a = range(n) b = 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
2、numpy实现
#向量相加 - numpy import numpy def numpyvector(n): a = numpy.arange(n) ** 2 b = numpy.arange(n) ** 3 c = a + b return c
#效率比较 import sys from datetime import datetime n = 1000 start = datetime.now() c = pythonvector(n) end = datetime.now() -start print "The last 3 elements of the result ",c[-3:] print "pythonvector elapsed time ",end.microseconds start = datetime.now() c = numpyvector(n) end = datetime.now() -start print "The last 3 elements of the result ",c[-3:] print "numpyvector elapsed time ",end.microseconds
结果是一样的,效率上numpy远快于原生的python,并且写法上更简洁。