gpt4 book ai didi

arrays - 与在 Julia 中生成 Float 数组相比,将整数数组乘以 Float 会提高还是降低性能?

转载 作者:行者123 更新时间:2023-12-03 21:59:17 24 4
gpt4 key购买 nike

我想知道是否表达dx*collect(0:J)哪里JInt64dxFloat64在计算上比 collect(0:dx:dx*J) 更有效或者反过来?

换种说法:生成整数数组并乘以 (J+1) 次乘以浮点数(第一种情况)还是首先生成浮点数数组(第二种情况)更有效?

每个案例的好处/缺点是什么?

最佳答案

我相信周围会有一些人可以就 LLVM 等生成的代码给你一个完整的解释,但在像这样的简单情况下,当你有疑问时,你可以只进行基准测试:

julia> using BenchmarkTools

julia> collect_first(dx, J) = dx*collect(0:J)
collect_first (generic function with 1 method)

julia> collect_all(dx, J) = collect(0:dx:dx*J)
collect_all (generic function with 1 method)

julia> @btime collect_first(3.2, 100);
172.194 ns (2 allocations: 1.75 KiB)

julia> @btime collect_all(3.2, 100);
359.330 ns (1 allocation: 896 bytes)

julia> @btime collect_first(3.2, 10_000);
11.300 μs (4 allocations: 156.53 KiB)

julia> @btime collect_all(3.2, 10_000);
18.601 μs (2 allocations: 78.27 KiB)

julia> @btime collect_first(3.2, 100_000);
145.499 μs (4 allocations: 1.53 MiB)

julia> @btime collect_all(3.2, 100_000);
183.300 μs (2 allocations: 781.39 KiB)

julia> @btime collect_first(3.2, 1_000_000);
5.650 ms (4 allocations: 15.26 MiB)

julia> @btime collect_all(3.2, 1_000_000);
3.806 ms (2 allocations: 7.63 MiB)

因此,如果您先收集,则会将分配数量加倍(大概是因为分配发生在 collect 上,然后在乘法以获得输出时再次发生),但是对于小数组,这似乎在计算时间方面仍然更快。对于在乘以范围后收集的大型数组,严格占主导地位。

关于arrays - 与在 Julia 中生成 Float 数组相比,将整数数组乘以 Float 会提高还是降低性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60632489/

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