我将两个大矩阵相乘,并且当我第一次对第一个输入执行求幂时,操作更快:
import time
import numpy as np
a = np.asarray(np.random.uniform(-1,1, (100,40000)), dtype=np.float32)
b = np.asarray(np.random.uniform(-1,1, (40000,20000)), dtype=np.float32)
start = time.time()
d0 = np.dot(a,b)
print "\nA.B - {:.2f} seconds".format((time.time()-start))
start = time.time()
d1 = np.dot(np.exp(a), b)
print "exp(A).B - {:.2f} seconds".format((time.time()-start))
start = time.time()
d2 = np.dot(a, np.exp(b))
print "A.exp(B) - {:.2f} seconds".format((time.time()-start))
start = time.time()
d3 = np.dot(np.exp(a), np.exp(b))
print "exp(A).exp(B) - {:.2f} seconds".format((time.time()-start))
结果如下:
A.B 1.27 seconds
exp(A).B 1.15 seconds
A.exp(B) 7.31 seconds
exp(A).exp(B) 7.38 seconds
任何人都可以解释我做错了什么,或者这怎么可能?
答案 0 :(得分:2)
您所看到的是您在进行基准测试时永远不会只运行一次操作的原因,这就是您在此处尝试的内容。当你只做一次时,许多事情会影响你所看到的结果。在这种情况下,可能是一些缓存效果。此外,b数组比数组大得多,除非您在非常受控的环境中运行,否则在执行initialize
时无法与class Command
attr_reader :input, :robotic_rover
def initialize(input, robotic_rover)
@input = input
@robotic_rover = robotic_rover
end
def position_change
robotic_rover.move if input == 'M'
robotic_rover.right_turn if input == 'R'
robotic_rover.left_turn if input == 'L'
end
end
vs a
得出任何结论
为了更准确地对此进行基准测试,我们可以削减最后两个基准,并专注于np.exp(a)
vs np.exp(b)
。此外,我们重复操作10,000次并减少阵列的大小,以避免等待几分钟:
a
这会在我的电脑上产生以下结果:
exp(a)
如您所见,正如预期的那样,执行import time
import numpy as np
a = np.asarray(np.random.uniform(-1,1, (100,400)), dtype=np.float32)
b = np.asarray(np.random.uniform(-1,1, (400,2000)), dtype=np.float32)
start = time.time()
for i in xrange(10000):
d0 = np.dot(a,b)
print "\nA.B - {:.2f} seconds".format((time.time()-start))
start = time.time()
for i in xrange(10000):
d0 = np.dot(np.exp(a), b)
print "exp(A).B - {:.2f} seconds".format((time.time()-start))
所花费的时间比仅仅访问A.B - 7.87 seconds
exp(A).B - 13.24 seconds
需要更多时间。
答案 1 :(得分:1)
我怀疑这是内存缓存的问题,因为颠倒了执行的顺序
import time
import numpy as np
a = np.asarray(np.random.uniform(-1,1, (100,4000)), dtype=np.float32)
b = np.asarray(np.random.uniform(-1,1, (4000,20000)), dtype=np.float32)
start = time.time()
d1 = np.dot(np.exp(a), b)
print "exp(A).B - {:.2f} seconds".format((time.time()-start))
start = time.time()
d0 = np.dot(a,b)
print "A.B - {:.2f} seconds".format((time.time()-start))
start = time.time()
d1 = np.dot(np.exp(a), b)
print "exp(A).B - {:.2f} seconds".format((time.time()-start))
start = time.time()
d0 = np.dot(a,b)
print "A.B - {:.2f} seconds".format((time.time()-start))
仍然会导致第二个语句比第一个语句更快,但是第二次执行相同的语句也会在第二次执行时更快。
exp(A).B - 0.72 seconds
A.B - 0.70 seconds
exp(A).B - 0.70 seconds
A.B - 0.69 seconds
(我不得不减少数组的大小以避免内存问题。)