How much time did it take?
sleep method is used to suspend the current thread for some amount of time. Lets look at a simple way to measure the actual time that the method can take to completely execute:
And now, I want you to use Ruby's super-awesome blocks to create a method which takes in a block, executes it, and returns the time it took.
The Ruby standard library has a
Benchmark class - it can do what the code in the above exercise can, and more. Let us take it for a quick spin!
measure method gives you the time taken to execute the block of code - similar to the exercise we just solved. It is already present in the Ruby standard library, has more functionality and is easy to use.
Now let us break down those numbers a bit. The first column is the "user cpu time". This is the time spent by the code executing userspace code (in our case, the code we've written and the Ruby library methods that are invoked by that code).
The second column is "system cpu time" - this is the time taken by the system (kernel) to execute any system level functions needed by your code.
The third column is the sum of both the cpu and user times - it is the total amount of time spent by the CPU to execute your code - this includes the user cpu time, system cpu time and any time spent waiting because the cpu had nothing to do. This wait is due to the time taken for I/O (disk reads and writes, network wait etc.) to happen.
A common use case of benchmarking is to compare the performance of different implementations of the same functionality. The
Benchmark class provides the method
bm for this.
As you can see in the above benchmark, using the << operator or
map is faster than building a new array to add each number.
A lesson that talks about benchmarking and code optimization is not complete without Donald Knuth's piece of wisdom: "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil". Optimization is best left for the last - once you have identified the exact places where performance bottlenecks happen and optimize just them. More on premature optimization on the c2 wiki.