How to measure Ruby method performance ?

Hey Guys,

Today, we will use our reverse methods that we have built in the previous post and measure how good they are comparing to the Ruby built in reverse method. For this purpose we will use Ruby Benchmark Module.

All we need to do is wrap everything in Benchmark block, and every single method we want to examine in the report block. As you can see from the code below, I am also passing custom headers to differentiate methods.

def time_required_comparison
  Benchmark.bm do |bm|
	bm.report('c-rev-string') do
		reverse_whole_string('Welcome to myprogrammingblog')
	end
	bm.report('s-rev-string') do
		'Welcome to myprogrammingblog'.reverse
	end

	bm.report('c-rev-words') do
		reverse_each_word_in_a_string('Welcome to myprogrammingblog')
	end
	bm.report('s-rev-words') do
		'Welcome to myprogrammingblog'.split(' ').each {|word| word.reverse!}.join(' ')
	end

	bm.report('c-rev-word-order') do
		reverse_word_order_in_a_sentence('Welcome to myprogrammingblog')
	end
	bm.report('s-rev-word-rder') do
		'Welcome to myprogrammingblog'.split.reverse.join(' ')
	end

  end
end

For a full source code please refer here .

The output of this code will look like this:

             user     system      total        real
c-rev-string 0.000000 0.000000 0.000000 ( 0.000009)
s-rev-string 0.000000 0.000000 0.000000 ( 0.000002)
c-rev-words 0.000000 0.000000 0.000000 ( 0.000011)
s-rev-words 0.000000 0.000000 0.000000 ( 0.000004)
c-rev-word-order 0.000000 0.000000 0.000000 ( 0.000004)
s-rev-word-rder 0.000000 0.000000 0.000000 ( 0.000003)

What we really care about is ‘real’ runtime, which shows how long it took to execute this method.

We can see that all of the methods are as British would say ran “bloody” fast. We can also see that, for example ,Ruby’s built in reverse method is much faster than my implementation (If it wasn’t so, I would write my own programming language, right? 🙂 ).

Benchmark Module is very helpful to quickly determine if there is a bottleneck in your implementation, also useful to determine what library to choose based on the real runtimes.

For more advanced profiling, many Ruby developers suggest to use  ruby-prof gem. We will definitely cover it in one of the future posts.

That was it for today,

You have a “Lovely” day. (I am in British mood today 🙂 )

Anatoly

Thanks for installing the Bottom of every post plugin by Corey Salzano. Contact me if you need custom WordPress plugins or website design.

Anatoly Spektor

IT Consultant with 6 years experience in Software Development and IT Leadership. Participated in such projects as Eclipse IDE, Big Blue Button, Toronto 2015 Panam Games.

Join the Discussion

Your email address will not be published. Required fields are marked *

Discussion

  1. Please check my gem for benchmarking ruby methods https://github.com/igorkasyanchuk/benchmark_methods

arrow