Ruby Benchmark
You want to write fast code right? Of course you do. The question is how you can do it.
There are certainly different specific ways to optimize different parts of code but if you don’t know which way is fastest then you can always test the code to find out. That is where Ruby’s Benchmark module comes in.
Today, we’ll learn about Ruby’s Benchmark module which is used to measure the speed of your code.
Basic Measurement
The simplest way to measure code performance is using the Benchmark.measure
method. Here’s a basic example:
require 'benchmark'
puts Benchmark.measure { (0..9999999).each{|n| n * 99999999} }
# user system total real
# => 0.770000 0.010000 0.780000 ( 0.773784)
So what is in that output?
- User: CPU time spent in user-mode code (your Ruby code)
- System: CPU time spent in kernel-mode code (system calls)
- Total: Combined user and system time
- Real: Actual elapsed wall-clock time
Comparing Multiple Code Implementations with Benchmark.bm
If you want to compare two or more bits of Ruby code that do the same thing and see how fast they are against each other then you can use the ‘bm’ method on Benchmark.
require 'benchmark'
Benchmark.bm do |z|
z.report { x = 0; (0..9999999).each{|n| x += n * 99999999} }
z.report { x = (0..9999999).map{|n| n * 99999999}.sum }
z.report { x = 0; for n in 0..9999999; x += n * 99999999; end }
end
user system total real
1.123505 0.003602 1.127107 ( 1.127646)
0.608362 0.028901 0.637263 ( 0.637416)
1.139016 0.005494 1.144510 ( 1.144769)
The example above demonstrates three different ways to assign a number to x
by enumerating of a range and multiplying the number. This is a simple example and not likely to be something you would actually use but it gets the point across how to use Benchmark.