How To Benchmark In Ruby

Benchmarking is a simple and effective way to measure the performance of your code. It is particularly useful when you are trying to optimize your code or compare different algorithms. In this blog post, we will discuss how to benchmark your Ruby code using the built-in benchmark module and a popular gem called benchmark-ips.

Using the Built-in Benchmark Module

Ruby comes with a built-in module called benchmark that provides methods to measure and report the time taken to execute your code. To use the benchmark module, you need to require it in your code:

require 'benchmark'
    

Here’s a simple example of using the benchmark module to measure the time taken to execute a piece of code:

require 'benchmark'

time = Benchmark.measure do
  sum = 0
  1.upto(1_000_000) { |i| sum += i }
end

puts "Time taken: #{time}"
    

This will output the time taken to execute the code block in seconds. The Benchmark.measure method returns an object containing the following attributes:

  • real: Total time taken to run the code.
  • user: User CPU time.
  • system: System CPU time.
  • cstime: User CPU time of children.
  • cutime: System CPU time of children.
  • total: Total CPU time (user + system).

Using the Benchmark-ips Gem

The benchmark-ips gem is a popular benchmarking tool that provides an easy way to compare the performance of different implementations. It measures the number of iterations your code can perform in a second, which is a more accurate representation of performance than just measuring the total time taken.

To start using benchmark-ips, you need to install the gem:

gem install benchmark-ips
    

Now, let’s see how to use benchmark-ips to compare the performance of two different algorithms for calculating the sum of the first 1,000,000 numbers:

require 'benchmark/ips'

def sum_using_loop
  sum = 0
  1.upto(1_000_000) { |i| sum += i }
end

def sum_using_formula
  (1_000_000 * (1_000_000 + 1)) / 2
end

Benchmark.ips do |x|
  x.report("Using loop") { sum_using_loop }
  x.report("Using formula") { sum_using_formula }
  x.compare!
end
    

This code will output something like this:

Using loop:       340.8 i/s
Using formula: 14268271.0 i/s - 41.86x  (± 0.00) slower
    

As you can see, the output shows the number of iterations per second for each algorithm, and also provides a comparison of their performance.

Benchmark-ips is an excellent tool for comparing the performance of different algorithms and optimizing your Ruby code.

Conclusion

Benchmarking is crucial for optimizing your Ruby code and comparing the performance of different algorithms. The built-in benchmark module and the benchmark-ips gem are both powerful tools that can help you achieve this goal. Start using these tools to measure and improve the performance of your Ruby code.