import numpy as np
from math import sin as sn
import matplotlib.pyplot as plt
import time
# 测试数量
N_point = 1000
# 定义一个有if else循环的函数
def myfunc(x,y):
if (x>0.5*y and y<0.3): return (sn(x-y))
elif (x<0.5*y): return 0
elif (x>0.2*y): return (2*sn(x+2*y))
else: return (sn(y+x))
# 从正态分布产生存储元素的列表
lst_x = np.random.randn(N_point)
lst_y = np.random.randn(N_point)
lst_result = []
# 可选择画出数据分布
plt.hist(lst_x,bins=20)
plt.show()
plt.hist(lst_y,bins=20)
plt.show()
# 首先,纯粹的Python代码
t1=time.time()
First, plain vanilla for-loop
t1=time.time()
for i in range(len(lst_x)):
x = lst_x[i]
y= lst_y[i]
if (x>0.5*y and y<0.3):
lst_result.append(sn(x-y))
elif (x<0.5*y):
lst_result.append(0)
elif (x>0.2*y):
lst_result.append(2*sn(x+2*y))
else:
lst_result.append(sn(y+x))
t2=time.time()
print("nTime taken by the plain vanilla for-loopn----------------------------------------------n{} us".format(1000000*(t2-t1)))
# List comprehension
print("nTime taken by list comprehension and zipn"+'-'*40)
%timeit lst_result = [myfunc(x,y) for x,y in zip(lst_x,lst_y)]
# Map() 函数
print("nTime taken by map functionn"+'-'*40)
%timeit list(map(myfunc,lst_x,lst_y))
# Numpy.vectorize 方法
print("nTime taken by numpy.vectorize methodn"+'-'*40)
vectfunc = np.vectorize(myfunc,otypes=[np.float],cache=False)
%timeit list(vectfunc(lst_x,lst_y))
# 结果
Time taken by the plain vanilla for-loop
----------------------------------------------
2000.0934600830078 us
Time taken by list comprehension and zip
----------------------------------------
1000 loops, best of 3: 810 µs per loop
Time taken by map function
----------------------------------------
1000 loops, best of 3: 726 µs per loop
Time taken by numpy.vectorize method
----------------------------------------
1000 loops, best of 3: 516 µs per