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



我正在尝试在有关全局变量问题的代码中应用以下性能提示: https://docs.julialang.org/en/v1/manual/performance-tips/

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

现在我有一个名为minus_func的插值函数(通过插值Interpolations.jl中的数组获得(,其类型通过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"))}

这个minus_func被声明为全局变量,并且会在循环中被多次调用(并且可能会被更改,所以我不喜欢将其声明为const(。是否可以在调用其类型时对其进行注释,以便提高性能?如果是这样,如何?如以下示例所示,其中x注释为类型Vector{Float64}

global x = rand(1000)
function loop_over_global()
s = 0.0
for i in x::Vector{Float64}
s += i
end
return s
end

那么,鉴于minus_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)

最新更新