Skip to content

Commit d8b44f9

Browse files
committed
Refactor to better support running multiple benchmarks
1 parent 6571c26 commit d8b44f9

1 file changed

Lines changed: 41 additions & 12 deletions

File tree

tools/snippets/benchmark/julia/benchmark.jl

Lines changed: 41 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@
33
import BenchmarkTools
44

55
# Benchmark variables:
6-
name = "TODO";
76
repeats = 3;
7+
samples = 1e6;
8+
count = 0;
89

910
"""
1011
print_version()
@@ -73,7 +74,7 @@ function print_results( iterations, elapsed )
7374
end
7475

7576
"""
76-
benchmark()
77+
benchmark( expr )
7778
7879
Run a benchmark.
7980
@@ -83,14 +84,18 @@ Run a benchmark.
8384
* The number of iterations is not the true number of iterations. Instead, an 'iteration' is defined as a 'sample', which is a computed estimate for a single evaluation.
8485
* The elapsed time is in seconds.
8586
87+
# Arguments
88+
89+
* `expr`: expression to benchmark
90+
8691
# Examples
8792
8893
``` julia
89-
julia> out = benchmark();
94+
julia> out = benchmark( :( sin( 3.14 ) ) );
9095
```
9196
"""
92-
function benchmark()
93-
t = BenchmarkTools.@benchmark TODO samples=1e6
97+
function benchmark( expr )
98+
t = eval( :( BenchmarkTools.@benchmark $expr samples=$samples ) )
9499

95100
# Compute the total "elapsed" time and convert from nanoseconds to seconds:
96101
s = sum( t.times ) / 1.0e9;
@@ -102,6 +107,32 @@ function benchmark()
102107
[ iter, s ];
103108
end
104109

110+
"""
111+
bench( name, expr )
112+
113+
Run a named benchmark.
114+
115+
# Arguments
116+
117+
* `name`: benchmark name (suffix)
118+
* `expr`: expression to benchmark
119+
120+
# Examples
121+
122+
``` julia
123+
julia> bench( "sin", :( sin( 3.14 ) ) );
124+
```
125+
"""
126+
function bench( name, expr )
127+
for i in 1:repeats
128+
@printf( "# julia::%s\n", name );
129+
global count += 1;
130+
results = benchmark( expr );
131+
print_results( results[ 1 ], results[ 2 ] );
132+
@printf( "ok %d benchmark finished\n", count );
133+
end
134+
end
135+
105136
"""
106137
main()
107138
@@ -115,13 +146,11 @@ julia> main();
115146
"""
116147
function main()
117148
print_version();
118-
for i in 1:repeats
119-
@printf( "# julia::%s\n", name );
120-
results = benchmark();
121-
print_results( results[ 1 ], results[ 2 ] );
122-
@printf( "ok %d benchmark finished\n", i );
123-
end
124-
print_summary( repeats, repeats );
149+
150+
# Run benchmark:
151+
bench( "TODO", :( TODO ) );
152+
153+
print_summary( count, count );
125154
end
126155

127156
main();

0 commit comments

Comments
 (0)