朱莉娅 - 为什么在模块中包含变量会占用如此多的内存?

时间:2017-09-22 20:38:17

标签: performance julia

考虑这两个功能:

功能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相同) }})。为什么呢?

1 个答案:

答案 0 :(得分:3)

r模块中的

params是非const全局,这会使其类型不稳定(因为某些函数可以将r分配给其他类型的不同类型)。

r = 3替换为const r = 3,时间将相同。另请参阅Performance Tips的第一部分。