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

Performance 朱莉娅-为什么在模块中包含变量会占用这么多内存?,performance,julia,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

考虑这两个功能:

职能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
并在
testVec2
中包含
r
,而不使用前缀
params
,则其性能会立即提高(与
testVec
相同)。为什么?

r
params
模块中,它是一个非
const
全局模块,这使得它的类型不稳定(因为某些函数可以将
r
分配给其他类型的对象)


r=3
替换为
const r=3
,计时将相同。另请参见的第一节。

谢谢。有没有办法检查变量的类型是否不稳定?例如,一个函数,如
isstastable()
?Doing
@code\u warntype testVec2([1 2 3 4],[2 3 4 5],[3 4 5 6],1000)
提供了大量有关Julia编译器在计算中分配给变量和中间值的类型的信息。注意任何红色的任何类型批注都是有问题的线索。@tryingtosolve在
Base.Test
中还有一个
@推断的
宏。