考虑这两个功能:
功能1:
function testVec(t,v,k,n)
for i=1:n
t .= v .* 3 .+ k .* 4;
end
end
功能2:
module params
r = 3;
end
function testVec2(t,v,k,n)
for i=1:n
t .= v .* params.r .+ k .* 4;
end
end
他们的表现截然不同:
@time testVec([1 2 3 4], [2 3 4 5], [3 4 5 6], 1000)
0.000036 seconds (7 allocations: 496 bytes)
@time testVec2([1 2 3 4], [2 3 4 5], [3 4 5 6], 1000)
0.003180 seconds (4.01 k allocations: 141.109 KiB)
为什么在模块中包含参数r
会使函数执行得更糟?
如果我export
模块params
并在r
中包含testVec2
而不使用前缀params
,则其效果会立即提升(与{{1相同) }})。为什么呢?
答案 0 :(得分:3)
r
模块中的 params
是非const
全局,这会使其类型不稳定(因为某些函数可以将r
分配给其他类型的不同类型)。
将r = 3
替换为const r = 3
,时间将相同。另请参阅Performance Tips的第一部分。