In Ruby, you have to perform benchmarking to measure performance of your code. Ruby allows you to do Benchmarking using library called ‘benchmark’
You have to include library before you start with Benchmarking.
Let us see example of how you can perform benchmarking in Ruby.
It will allow you to use Benchmark library.
Now, suppose you have two code blocks which you have to compare,
Let us say we have array a and b,
Now, you have to push the element 5 into these arrays. Let’s perform this operation 1000000 times so that it will take significant amount of time by which we can compare these two operations or code blocks.
Code block 1:
Code block 2:
1. Benchmark bm method
So, the Benchmarking performance shows user time, system time, total time and real time taken by code block to execute. As we reported performance of two blocks the result was performance of two blocks.
From the result it is clear that array insert («) is faster than array push.
Find more about array insert and array push.
You can also perform benchmarking as,
2. Benchmark bmbm method
Basically, bmbm is used so that Garbage Collection that takes place before each operation should not affect the result and we should get consistent result.
- bmbm performs rehearsal for the first time and then performs actual operation so that we can get consistent results.
- So, by now you would be comfortable with measuring performance of various code blocks if you want.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox