Benchmarking Ruby code 101

Benchmarking Ruby code 101

There are a lot of times when I wonder if writing code using one way would be faster than the other esp now days when there are 10 different ways of doing the same thing. Here is how this can be done in Ruby.

Classic way

There is the classic way to do it, works everywhere and has similar implementation in all languages.

time

Benchmark

Benchmark is a module in Ruby's standard library which does exactly this!

Benchmark.measure takes a code block runs it and reports how long it took, this can be printed in the console using puts

benchmark

Alternatively one can use Benchmark.bm to run multiple lines at once.

benchmulti

The output for measure is something like this

out

which basically shows the user CPU time, system CPU time, the sum of the user and system CPU times, and the elapsed real time. The unit of time is seconds.

LPT: A lot of common idioms are pre-benchmarked, and their results are published as fast-ruby. Reading through the examples can save you some benchmarking in the future.