Numpy:两个版本的矩阵乘法,相同的操作数但速度却截然不同?

时间:2017-01-10 13:01:36

标签: python numpy optimization

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倍。为什么?

0 个答案:

没有答案