Julia - 在struct中浏览数组的许多分配

问题描述 投票:0回答:2

我目前正在努力应对朱莉娅的怪异行为。我正在浏览一个数组,无论数组是否在结构内部,Julia的行为都不一样。

在结构中的数组的情况下,有许多分配似乎毫无意义。具体而言,与阵列的大小一样多的分配。

这是一个复制此问题的代码:

function test1()
    a = ones(Float32, 256)

    for i = 1:256
        a[i]
    end
end

struct X
    mat
end

function test2()
    a = X(ones(Float32, 256))

    for i = 1:256
        a.mat[i]
    end
end

function main()
    test1()
    test2()

    @time test1()
    @time test2()
end

main()

我得到的输出:

0.000002 seconds (1 allocation: 1.141 KiB)
0.000012 seconds (257 allocations: 5.141 KiB)

起初我认为这是一个类型问题,但我没有强迫它,循环后类型没有不同。

谢谢你的帮助。

arrays struct julia allocation
2个回答
2
投票

您需要在mat中指定struct的类型。否则,使用X的函数将不会专门化并进行足够的优化。

没有类型注释的字段默认为Any,因此可以保存任何类型的值。 https://docs.julialang.org/en/v1/manual/types/index.html#Composite-Types-1

将结构定义更改为

struct X
    mat::Vector{Float32}
end

将解决问题。结果现在是:

  0.000000 seconds (1 allocation: 1.141 KiB)
  0.000000 seconds (1 allocation: 1.141 KiB)

如果您在代码中更改了一件事,您实际上可以通过@code_warntype宏看到效果。

for i = 1:256
    a.mat[i]
end

这部分并没有真正做多少。要查看@code_warntype的效果,请将旧代码中的此行更改为

for i = 1:256
    a.mat[i] += 1.
end

@code_warntype的结果将给出红色的Any,你通常应该避免。原因是在编译时不知道mat的类型。

> @code_warntype test2() # your test2() with old X def
Body::Nothing
1 ─ %1  = $(Expr(:foreigncall, :(:jl_alloc_array_1d), Array{Float32,1}, svec(Any, Int64), :(:ccall), 2, Array{Float32,1}, 256, 256))::Array{Float32,1}
│   %2  = invoke Base.fill!(%1::Array{Float32,1}, 1.0f0::Float32)::Array{Float32,1}
└──       goto #7 if not true
2 ┄ %4  = φ (#1 => 1, #6 => %14)::Int64
│   %5  = φ (#1 => 1, #6 => %15)::Int64
│   %6  = (Base.getindex)(%2, %4)::Any <------ See here
│   %7  = (%6 + 1.0)::Any
│         (Base.setindex!)(%2, %7, %4)
│   %9  = (%5 === 256)::Bool
└──       goto #4 if not %9
3 ─       goto #5
4 ─ %12 = (Base.add_int)(%5, 1)::Int64
└──       goto #5
5 ┄ %14 = φ (#4 => %12)::Int64
│   %15 = φ (#4 => %12)::Int64
│   %16 = φ (#3 => true, #4 => false)::Bool
│   %17 = (Base.not_int)(%16)::Bool
└──       goto #7 if not %17
6 ─       goto #2
7 ┄       return

现在有了qazxsw poi的新定义,你会在qazxsw poi的结果中看到每种类型都被推断出来。

如果你想让X持有其他类型的@code_warntypes或值,你可能想要使用Parametric Types。使用参数类型,编译器仍然可以优化您的函数,因为在编译期间将知道类型。我真的建议你阅读X.matVector的相关手册。


2
投票
  1. 切勿在结构定义中使用抽象类型。在您的示例中,Julia需要存储变量指针而不仅仅是值,因此速度会降低。而是使用参数类型:
types
  1. 如果不确定,请考虑使用performance tips宏来查看Julia编译器无法正确识别类型的位置。
© www.soinside.com 2019 - 2024. All rights reserved.