Benchmarking Ruby

Tram Ho

Introduce

Benchmarking in ruby ​​is an essential tool for you to evaluate the hair of a code, a certain block of code in Ruby, from which can give other solutions to solve problems to increase the speed of the program. . In Ruby’s Standard Library, we provide a Benchmark module that can be used to measure the runtime of any block code. To use it, we just need:

Benchmarking a block code

To benchmarking a simple block code, we use the #measure method

We can see the result is returned in seconds, so the initialization of 10 million Objects takes just over a second.

If we want to print the result with a message, we can do the following:

Very simple is not it.

Comparison of code blocks

A problem is posed, there are always many different solutions, as is the code. So choosing the best, fast and accurate way is really a very difficult thing, especially for complex logic-processing blocks, then Benchmark is the tool used to compare the blockcode. For example:

In the above two methods, for the second method, using recursive speed, it will be very slow if n is a big number, use the #bm method to see the difference:

The first argument of the #bm method specifies the width of the label (dp, recursive), to align the displayed value to the left.

We can see that, for the #fib_rec function to finish running, it takes more than 1.5 seconds, and for the #fib_dp function, the execution time is insignificant, in fact, the #fib_dp function can run very fast when Large n, we can clearly see the following:

with n=100_000 , the #fib_dp function ran out of 0.35 seconds while with n=35 , the #fib_rec function had to run for more than 1.5 seconds.

Use benchmark-ips

benchmark-ips is a gem that gives us more features than the default Benchmark module. To use it, you need to install it and require into your program.

Use the gem above to test the following methods:

The only difference is x.compare! call x.compare! at the end of the block. We can see from the gem benchmark / ips that many other information of the two methods are printed to the screen such as the number of iterations per second, the standard deviation and finally the comparison shows that the #fib_rec method is not optimized. 100 000 times slower than the #fib_dp method

Conclude

If you’ve ever wondered why Enumerable#each faster than the for loop or [].map.flatten slower than [].flat_map , you can go to fast-ruby there with the correct answers to the problem. above, we can see the application of Benchmark in comparing the speed of methods available in ruby, thereby considering the use of methods in a logical and scientific manner.

Finally, it can be said that the Benchmark module and benchmark-ips gem are really easy to use and are essential for a Ruby developer program to increase performance.

Refer

http://mitrev.net/ruby/2015/08/28/benchmarking-ruby/

Share the news now

Source : Viblo