The Benchmark module provides methods for benchmarking Crystal code, giving detailed reports on the time taken for each task.
require "benchmark"
Benchmark.ips do |x|
x.report("short sleep") { sleep 0.01 }
x.report("shorter sleep") { sleep 0.001 }
end
This generates the following output:
short sleep 91.82 (± 1.11) 8.72× slower
shorter sleep 800.98 (± 4.72) fastest
Benchmark::IPS defaults to 2 seconds of warmup time and 5 seconds of
calculation time. This can be configured:
Benchmark.ips(warmup: 4, calculation: 10) do |x|
# …
end
Make sure to always benchmark code by compiling with the --release flag.
"a"*1_000_000_000require "benchmark"
puts Benchmark.measure { "a"*1000000000 }
This generates the following output:
0.190000 0.220000 0.410000 ( 0.420185)
This report shows the user CPU time, system CPU time, the sum of the user and system CPU times, and the elapsed real time. The unit of time is seconds.
#bm method:require "benchmark"
n = 5000000
Benchmark.bm do |x|
x.report("times:") { n.times do ; a = "1"; end }
x.report("upto:") { 1.upto(n) do ; a = "1"; end }
end
The result:
user system total real
times: 0.010000 0.000000 0.010000 ( 0.008976)
upto: 0.010000 0.000000 0.010000 ( 0.010466)
Make sure to always benchmark code by compiling with the --release flag.
Main interface of the Benchmark module.
Instruction per second interface of the Benchmark module.
Returns the time used to execute the given block.
Returns the elapsed real time used to execute the given block.
Main interface of the Benchmark module. Yields a Job to which
one can report the benchmarks. See the module's description.
Instruction per second interface of the Benchmark module. Yields a Job
to which one can report the benchmarks. See the module's description.
The optional parameters calculation and warmup set the duration of
those stages in seconds. For more detail on these stages see
Benchmark::IPS.
Returns the time used to execute the given block.
Returns the elapsed real time used to execute the given block.
Benchmark.realtime { "a" * 100000 } #=> 00:00:00.0005840