Julia のベンチマークテスト:@times と BenchmarkTools の @benchmark
まだ BenchmarkTools をインストールしていないなら,まずはパッケージのインストール。
(@v1.5) pkg> add BenchmarkTools
Updating registry at `~/.julia/registries/General`
######################################################################## 100.0%
Resolving package versions...
Installed BenchmarkTools ─ v0.5.0
Updating `~/.julia/environments/v1.5/Project.toml`
[6e4b80f9] + BenchmarkTools v0.5.0
Updating `~/.julia/environments/v1.5/Manifest.toml`
[6e4b80f9] + BenchmarkTools v0.5.0
ベンチマークは,関数を対象にする。
2つの関数,f1, f2 を定義する。いずれも 3 つの引数の和をとるものだが,鶏を割くのに牛刀を用いるような sum([x, y, z]) と 単に x + y + z の足し算をする方法の比較。
julia> f1(x, y, z) = sum([x, y, z])
f1 (generic function with 1 method)
julia> f2(x, y, z) = x + y + z
f2 (generic function with 1 method)
@benchmark を使うときには一度だけ using が必要。
julia> using BenchmarkTools
[ Info: Precompiling BenchmarkTools [6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf]
実行する関数の前に @benchmark を付けるだけ。
julia> @benchmark f1(1, 2, 3)
BenchmarkTools.Trial:
memory estimate: 112 bytes
allocs estimate: 1
--------------
minimum time: 40.868 ns (0.00% GC)
median time: 43.567 ns (0.00% GC)
mean time: 47.606 ns (3.71% GC)
maximum time: 1.103 μs (95.23% GC)
--------------
samples: 10000
evals/sample: 991
julia> @benchmark f2(1, 2, 3)
BenchmarkTools.Trial:
memory estimate: 0 bytes
allocs estimate: 0
--------------
minimum time: 0.018 ns (0.00% GC)
median time: 0.032 ns (0.00% GC)
mean time: 0.028 ns (0.00% GC)
maximum time: 0.039 ns (0.00% GC)
--------------
samples: 10000
evals/sample: 1000
単に足し算する方が圧倒的に速い(まあ,ゴミのような差なので,比較する意味はないが)。
なお,何もしないで使える方法で @time を使うやり方もある。これは,関数を一度だけ実行した上でのの計測なので,振れ幅が大きい。
julia> @time f1(1, 2, 3)
0.000001 seconds (1 allocation: 112 bytes)
6
julia> @time f2(1, 2, 3)
0.000000 seconds
6
実行時間がかかるなあと思ったら,@benchmark してみるのがお勧めです。