Asmod4n/mruby-benchmark-plus
Benchmark class for mruby
mruby-benchmark
Benchmark class for mruby, similar to CRuby's built-in Benchmark module.
Description
This gem provides a Benchmark module for mruby that allows you to measure and compare the performance of your code. It uses mruby-chrono for precise timing and mruby-cpuusage for CPU usage measurements.
Installation
Add the following line to your build_config.rb:
MRuby::Build.new do |conf|
# ... (other configurations)
conf.gem github: 'Asmod4n/mruby-benchmark'
endDependencies
This gem depends on:
- mruby-chrono - for time measurement
- mruby-cpuusage - for CPU usage tracking
Usage
Benchmark.realtime
Returns the elapsed real time for executing the given block as a Float.
time = Benchmark.realtime do
# code to benchmark
1000000.times { |i| i * 2 }
end
puts "Time elapsed: #{time} seconds"Benchmark.measure
Measures the execution time of the given block and returns a Benchmark::Tms object.
result = Benchmark.measure do
1000000.times { |i| i * 2 }
end
puts result
# Output: user time, system time, total time, and real timeBenchmark.bm
Runs multiple benchmarks with formatted output.
Benchmark.bm(20) do |x|
x.report("multiplication:") { 1000000.times { |i| i * 2 } }
x.report("addition:") { 1000000.times { |i| i + 2 } }
x.report("division:") { 1000000.times { |i| i / 2 } }
endBenchmark.bmbm
Runs benchmarks twice - first as a rehearsal, then as the real measurement. This helps eliminate initialization overhead.
Benchmark.bmbm(20) do |x|
x.report("multiplication:") { 500000.times { |i| i * 2 } }
x.report("addition:") { 500000.times { |i| i + 2 } }
endBenchmark::Tms
The Tms class represents timing measurements with the following attributes:
utime- User CPU timestime- System CPU timecutime- User CPU time of child processescstime- System CPU time of child processesreal- Elapsed real timelabel- Optional label for the measurement
You can perform arithmetic operations on Tms objects:
tms1 = Benchmark.measure { sleep 0.1 }
tms2 = Benchmark.measure { sleep 0.2 }
total = tms1 + tms2
diff = tms2 - tms1Example
See example.rb for a complete example.
License
Apache-2.0 License - see LICENSE file for details.
Author
Hendrik Beskow