# 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](https://i.imgur.com/XgzXw2s.png)

## Benchmark

[Benchmark](https://ruby-doc.org/stdlib-2.5.3/libdoc/benchmark/rdoc/Benchmark.html) 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](https://i.imgur.com/uja5cvT.png)

Alternatively one can use __Benchmark.bm__ to run multiple lines at once.

![benchmulti](https://i.imgur.com/uz8Aqc7.png)

The output for measure is something like this

![out](https://i.imgur.com/l7aHFVw.png)

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](https://github.com/JuanitoFatas/fast-ruby). Reading through the examples can save you some benchmarking in the future.
