import numpy as np
import time
X = np.random.randn(200, 200)
Y = np.random.randn(200, 200)
#version 1
def judge(x):
if x>0:
return 1
return x
convert = np.frompyfunc(judge,1,1)
C = convert(Y)
t1 = time.time()
r = X.dot(C)
t2 = time.time()
print t2-t1 #0.479473829269
#version 2
Y[Y>0] = 1
print C==Y #True
t1 = time.time()
r = X.dot(Y)
t2 = time.time()
print t2-t1 #0.00127196311951
尽管两个操作数是相同的,但版本1需要0.479秒,而版本2需要0.001秒,比版本1快478倍。为什么?