import numpy as np import time def myfunc(a, b): if a>b: return a-b else: return a+b vfunc = np.vectorize(myfunc) t0=time.time() vfunc(np.random.randint(5,size=10000000), 2) t1=time.time() print('speed_times:'+str(t1-t0)) #speed_times:3.2735631465911865 t0=time.time() [myfunc(data, 2) for data in np.random.randint(5,size=10000000)] t1=time.time() print('speed_times:'+str(t1-t0))
结果:向量化后的并行运算速度要比普通的执行速度快很多
speed_times:2.7337491512298584
speed_times:9.00490427017212