原生python与numpy数组向量相加效率对比
2016-04-09 22:44
585 查看
原生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
3、效率对比
#效率比较
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,并且写法上更简洁。
计算一个数据元素的平方与立方之和
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
3、效率对比
#效率比较
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,并且写法上更简洁。
相关文章推荐
- python3.0与python2.0有哪些不同
- python编译错误的积累
- Python之fileinput
- filter,map,reduce,lambda(python3)
- sublime学习(五)搭建Python开发环境
- python调度框架APScheduler使用详解
- ?Python 练习实例11
- python操作mysql
- python学习入门第一天总结
- Python bisect - array bisection library
- 求助:python中深拷贝和浅拷贝的一道题目
- ubuntu无法打开software-center
- LeetCode Best Time to Buy and Sell Stock II
- Python random
- 据廖雪峰python3教程----python学习第十一天
- 使用Runtime.getRuntime().exec()在java中调用python脚本
- Python处理JSON
- Python3 print()函数sep,end,file参数用法练习
- LoadRunner使用odbc时报错can't get hostname for your address的解决方法
- 萌妹子Python入门指北(四)