numpy函数向量化,np.vectorize
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
多思考也是一种努力,做出正确的分析和选择,因为我们的时间和精力都有限,所以把时间花在更有价值的地方。

浙公网安备 33010602011771号