# Python中的向量相加和numpy中的向量相加效率比较

# -*-coding:utf-8-*-
#向量相加
def pythonsum(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 a,b,c

print pythonsum(4),type(pythonsum(4))
for arg in pythonsum(4):
print arg

([0, 1, 4, 9], [0, 1, 8, 27], [0, 2, 12, 36]) <type 'tuple'>
[0, 1, 4, 9]
[0, 1, 8, 27]
[0, 2, 12, 36]

def numpysum(n):
a = np.arange(n) ** 2
b = np.arange(n) ** 3
c = a + b
return a,b,c
(array([0, 1, 4, 9]), array([ 0,  1,  8, 27]), array([ 0,  2, 12, 36])) <type 'function'>
[0 1 4 9]
[ 0  1  8 27]
[ 0  2 12 36]

size = 1000
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

size = 1000
start1 = datetime.now()
c1 = numpysum(size)
delta1 = datetime.now() - start1
# print 'The last 2 elements of the sum',c1[-2:]
print 'numpySum elapsed time in microseconds',delta1.microseconds

pythonSum elapsed time in microseconds 1000
numpySum elapsed time in microseconds 0

10-10 9779
07-06 151
03-05 262
04-12 3万+
04-01 1802
03-28 972
12-04 395
04-09 5966
11-02 9878
12-04
06-23 1万+
08-10 3714
04-09 1974
04-14 1万+
04-17 2万+
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客