gpt4 book ai didi

performance - Julia 类型不稳定 : Array of LinearInterpolations

转载 作者:行者123 更新时间:2023-12-02 02:06:52 24 4
gpt4 key购买 nike

我正在尝试通过消除任何类型不稳定的来源来提高代码的性能。

例如,我有几个 Array{Any} 声明的实例,我知道它们通常会破坏性能。这是一个 LinearInterpolation 对象的二维数组的最小示例(与我的代码相比大大简化),即

n,m=5,5
abstract_arr=Array{Any}(undef,n+1,m+1)
arr_x=LinRange(1,10,100)

for l in 1:n
for alpha in 1:m
abstract_arr[l,alpha]=LinearInterpolation(arr_x,alpha.*arr_x.^n)
end
end

这样typeof(abstract_arr)给出Array{Any,2}

如何初始化 abstract_arr 以避免在此处使用 Array{Any}

对于条目是像 Dicts() 这样的结构的数组,我该如何执行此操作,其中 Dicts() 是 Fl​​oat64 的 2 元组的字典?

最佳答案

如果你进行理解,就会为你找出类型:

arr = [LinearInterpolation(arr_x, ;alpha.*arr_x.^n) for l in 1:n, alpha in 1:m]

isconcretetype(eltype(arr)) # true

当它可以预测类型和长度时,它会第一次生成正确的数组。当它不能时,它将根据需要加宽或延伸。因此,其中一些可能是 Vector{Int},还有一些 Vector{Union{Nothing, Int}}:

[rand()>0.8 ? nothing : 0 for i in 1:3]
[rand()>0.8 ? nothing : 0 for i in 1:3]
[rand()>0.8 ? nothing : 0 for i in 1:10]

关于performance - Julia 类型不稳定 : Array of LinearInterpolations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68309528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com