DEV Community

Cover image for How to Utilize Benchmarking in Ruby
aryaziai
aryaziai

Posted on

4 2

How to Utilize Benchmarking in Ruby

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.

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Okay, let's go

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay