首页 > 解决方案 > 与在 Julia 中生成 Float 数组相比,将整数数组乘以 Float 会提高还是降低性能?

问题描述

我想知道表达式 dx*collect(0:J)where JisInt64dxisFloat64在计算上是否比collect(0:dx:dx*J)或相反?

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

每种情况的好处/缺点是什么?

标签: arraysperformancejulia

解决方案


我相信周围会有一些人可以就 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,然后在乘以得到输出时再次发生),但是对于小型数组,就计算时间而言,这似乎仍然更快。对于在乘以范围后收集的大型数组,严格占优。


推荐阅读