A Simple Vanilla Ruby way to Benchmark Test your Code for Speed

In this example, I wanted to know speed differences between the .uniq and .to_set speed. Here’s a simple way to measure computational complexity:

# any_file_name.rb
require 'benchmark'
require 'set'

data = [
  { id: 1, color: "brown", status: "closed" },
  { id: 2, color: "yellow", status: "open" },
  { id: 3, color: "brown", status: "closed" },
  { id: 4, color: "brown", status: "open" },
  { id: 5, color: "red", status: "closed" },
  { id: 6, color: "blue", status: "open" },
  { id: 7, color: "green", status: "closed" },
  { id: 8, color: "green", status: "open" },
  { id: 9, color: "brown", status: "closed" },
  { id: 10, color: "red", status: "open" },
  { id: 11, color: "blue", status: "closed" },
  { id: 12, color: "yellow", status: "open" },
  { id: 13, color: "green", status: "open" },
  { id: 14, color: "yellow", status: "open" },
  { id: 15, color: "blue", status: "closed" },
  { id: 16, color: "blue", status: "closed" },
  { id: 17, color: "blue", status: "closed" },
  { id: 18, color: "green", status: "open" },
  { id: 19, color: "yellow", status: "open" },
  { id: 20, color: "brown", status: "closed" },
  { id: 21, color: "green", status: "closed" },
  { id: 22, color: "red", status: "closed" },
  { id: 23, color: "red", status: "open" },
  { id: 24, color: "red", status: "open" },
];

uniq_start = Time.now
data.uniq{ |x| x[:color] = "red" }
uniq_finish = Time.now
uniq_diff = uniq_finish - uniq_start

p (uniq_diff * 1_000_000).to_s # evaluates to something like 7.0

set_start = Time.now
data.to_set{ |x| x[:color] = "red" }
set_finish = Time.now
set_diff = set_finish - set_start

p (set_diff * 1_000_000).to_s # evaluates to something like 32.0

In the above code we assign variables to the start and end of each function. Then we run the methods and we finally print out the difference times a million so we get the millisecond computational complexity.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>