Easily compare performance of two implementations

Posted . Visible to the public.

Sometimes you have to decide between two or more ways on how to implement something. As developer, we make such decisions all day log. If you write code that has to be fast (e.g. because it runs often), comparing the performance of different implementations is key.
Ruby has a handy gem for that: benchmark-ips Show archive.org snapshot . Here's how to use it.

Gemfile:

gem "benchmark-ips"

Rails console or irb:

require 'benchmark/ips'

str = "gid://glibberish/Glib/12345"
Benchmark.ips do |x|
  x.report('regex-1') { str.gsub(/gid:\/\/[a-z]+\/[a-z]+\//i, "") }
  x.report('regex-2') { str.gsub(/gid:\/\/[^\\]+\/[^\\]+\//, "") }
end

Result:

Warming up --------------------------------------
             regex-1    93.843k i/100ms
             regex-2    82.249k i/100ms
Calculating -------------------------------------
             regex-1    959.574k (± 4.5%) i/s -      4.880M in   5.094075s
             regex-2    833.856k (± 3.6%) i/s -      4.195M in   5.036360s

How to read the results: Higher numbers ar better!

Benchmark/ips will report the number of iterations per second for a given block of code. When analyzing the results, notice the percent of standard deviation which tells us how spread out our measurements are from the average. A high standard deviation could indicate the results having too much variability.

Judith Roth
Last edit
Judith Roth
Keywords
Ruby, comparision, benchmark, measure, measuring
Posted by Judith Roth to Judith's Dev Notes (2022-10-14 09:42)