DEV Community

loading...
Cover image for How to Utilize Benchmarking in Ruby

How to Utilize Benchmarking in Ruby

aryaziai
"respect all life"
・2 min read

Overview

In this blog I'll be a sharing a short tutorial on how to test the execution time of your Ruby code. It makes things a little easier since Ruby comes packed with a module in its standard library built for benchmarking. The module is named Benchmark and we can utilize with just one line of code.

Environment

Before we utilize the module, we need to require Benchmark in our ruby file.

require 'benchmark'

Basic Usage

The most basic usage of the Benchmark:

require 'benchmark'

Benchmark.measure { 
  # code
}

Let's add a short loop and output the result:

require 'benchmark'

puts Benchmark.measure { 
  for i in 0..50
    puts "Value of local variable is #{i}"
 end
}

Result:

Alt Text

This result is ok but we're missing labels, and we're not comparing any methods to one another.

Advanced Usage

require 'benchmark'

n = 5000000
Benchmark.bm(20) do |x|
  x.report("for:")   { for i in 1..n; a = "1"; end }
  x.report("times:") { n.times do   ; a = "1"; end }
  x.report("upto:")  { 1.upto(n) do ; a = "1"; end }
end

Result:

Alt Text

In this example, the for loop had the quickest execution time.

Conclusion

I never knew how easy it was to test out the performance of my code in Ruby. If you'd like to learn more about Benchmarking in Ruby, check out the documentation.

Discussion (0)