Function 当插值函数必须作为全局变量多次访问时,优化Julia性能

Function 当插值函数必须作为全局变量多次访问时,优化Julia性能,function,global-variables,julia,Function,Global Variables,Julia,关于全局变量问题,我试图在我的代码中应用以下性能提示: 据我所知,为了提高性能,应该避免使用全局变量(特别是当必须在大循环中调用它们时),方法是将它们声明为const,尝试将它们用作局部变量,或者每次使用时都注释类型 现在我有一个插值函数(通过在Interpolations.jl中插值一个数组获得),名为minus_func,其类型通过typeof函数获得: getfield(Main, Symbol("#minus_func#877")){Interpolations.Extrapolati

关于全局变量问题,我试图在我的代码中应用以下性能提示:

据我所知,为了提高性能,应该避免使用全局变量(特别是当必须在大循环中调用它们时),方法是将它们声明为
const
,尝试将它们用作局部变量,或者每次使用时都注释类型

现在我有一个插值函数(通过在
Interpolations.jl
中插值一个数组获得),名为
minus_func
,其类型通过
typeof
函数获得:

getfield(Main, Symbol("#minus_func#877")){Interpolations.Extrapolation{Float64,3,ScaledInterpolation{Float64,3,Interpolations.BSplineInterpolation{Float64,3,OffsetArrays.OffsetArray{Float64,3,Array{Float64,3}},BSpline{Cubic{Line{OnCell}}},Tuple{Base.OneTo{Int64},Base.OneTo{Int64},Base.OneTo{Int64}}},BSpline{Cubic{Line{OnCell}}},Tuple{StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}},StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}},StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}}}},BSpline{Cubic{Line{OnCell}}},Periodic{Nothing}},getfield(Main, Symbol("#get_periodic#875"))}
这个
减号func
被声明为一个全局变量,并将在循环中被多次调用(并且可能会被更改,因此我不希望将其声明为
常量
)。在调用它时是否可以对其类型进行注释,以提高性能?如果是,怎么做?如以下示例所示,其中
x
被注释为类型
向量{Float64}

global x = rand(1000)

function loop_over_global()
    s = 0.0
    for i in x::Vector{Float64}
        s += i
    end
    return s
end
那么,如果
减号func
是全局的,那么如何以相同的方式提高以下代码的性能呢

function loop_over_global()
    s = 0.0
    for i in 1:1000
        s += minus_func(i, 1, 1)  # Let's say, the function takes three integer arguments
    end
    return s
end

您可以将全局参数设置为函数参数,使该函数参数不是全局参数:

using BenchmarkTools

function fminus(i, j, k)
    return i - k - j
end

minus_func = fminus

function loop_over_global()
    s = 0.0
    for i in 1:1000
        s += minus_func(i, 1, 1)
    end
    return s
end

function loop_over_global_witharg(f::Function)
    s = 0.0
    for i in 1:1000
        s += f(i, 1, 1)
    end
return s
end

@btime loop_over_global()
@btime loop_over_global_witharg(fminus)



  32.400 μs (1976 allocations: 30.88 KiB)
  949.958 ns (0 allocations: 0 bytes)