arrays - 与在 Julia 中生成 Float 数组相比,将整数数组乘以 Float 会提高还是降低性能?
问题描述
我想知道表达式
dx*collect(0:J)
where J
isInt64
和dx
isFloat64
在计算上是否比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
,然后在乘以得到输出时再次发生),但是对于小型数组,就计算时间而言,这似乎仍然更快。对于在乘以范围后收集的大型数组,严格占优。
推荐阅读
- vue.js - vue-cli 的问题:找不到模块'@babel/preset-env/data/built-ins.json'
- python - 递归二分搜索以检索目标的索引
- python - H2O.ai import_file 看起来不像懒惰的评估,它在做什么?
- jenkins - 詹金斯主页上的 ERR_CONNECTION_TIMED_OUT
- python - Python,使用 Popen 提交 qsub 作业
- unity3d - NPC不断走进墙壁 - Unity2D
- html - 在 VBA 中使用 ReactJS 选择 HTML 下拉列表
- javascript - 使用分层 .reduce() 或 .filter() 函数基于单独的搜索数组在对象数组中查找对象?
- javascript - 如何在 redux 中避免不可变
- c# - RestSharp,基本身份验证