gpt4 book ai didi

performance - 广播分配慢 Julia

转载 作者:行者123 更新时间:2023-12-04 02:39:53 25 4
gpt4 key购买 nike

我有这样的事情(简单的例子):

using BenchmarkTools
function assign()
e = zeros(100, 90000)
e2 = ones(100) * 0.16
e[:, 100:end] .= e2[:]
end
@benchmark assign()

并且需要数千个时间步长。这给了

BenchmarkTools.Trial: 
memory estimate: 68.67 MiB
allocs estimate: 6
--------------
minimum time: 16.080 ms (0.00% GC)
median time: 27.811 ms (0.00% GC)
mean time: 31.822 ms (12.31% GC)
maximum time: 43.439 ms (27.66% GC)
--------------
samples: 158
evals/sample: 1

有更快的方法吗?

最佳答案

首先我假设你的意思是

function assign1()
e = zeros(100, 90000)
e2 = ones(100) * 0.16
e[:, 100:end] .= e2[:]
return e # <- important!
end

否则您将不会返回 e(!) 的前 99 列:

julia> size(assign())
(100, 89901)

其次,不要这样做:

e[:, 100:end] .= e2[:]

e2[:] 复制 e2 并分配它,但为什么呢?直接赋值e2即可:

e[:, 100:end] .= e2

好的,但让我们尝试几个不同的版本。请注意,不需要将 e2 设为向量,只需分配一个标量即可:

function assign2()
e = zeros(100, 90000)
e[:, 100:end] .= 0.16 # Just broadcast a scalar!
return e
end

function assign3()
e = fill(0.16, 100, 90000) # use fill instead of writing all those zeros that you will throw away
e[:, 1:99] .= 0
return e
end

function assign4()
# only write exactly the values you need!
e = Matrix{Float64}(undef, 100, 90000)
e[:, 1:99] .= 0
e[:, 100:end] .= 0.16
return e
end

基准测试时间

julia> @btime assign1();
14.550 ms (5 allocations: 68.67 MiB)

julia> @btime assign2();
14.481 ms (2 allocations: 68.66 MiB)

julia> @btime assign3();
9.636 ms (2 allocations: 68.66 MiB)

julia> @btime assign4();
10.062 ms (2 allocations: 68.66 MiB)

版本 1 和 2 的速度同样快,但您会注意到有 2 个分配而不是 5 个,但是当然,大分配占主导地位。

第 3 版和第 4 版更快,但速度并不明显,但您会看到它避免了一些重复的工作,例如两次将值写入矩阵。版本 3 是最快的,不是很多,但是如果分配更平衡一点,情况就会改变,在这种情况下,版本 4 更快:

function assign3_()
e = fill(0.16, 100, 90000)
e[:, 1:44999] .= 0
return e
end

function assign4_()
e = Matrix{Float64}(undef, 100, 90000)
e[:, 1:44999] .= 0
e[:, 45000:end] .= 0.16
return e
end

julia> @btime assign3_();
11.576 ms (2 allocations: 68.66 MiB)

julia> @btime assign4_();
8.658 ms (2 allocations: 68.66 MiB)

教训是避免做不必要的工作。

关于performance - 广播分配慢 Julia ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60632800/

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