O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

17.12. Profiling Your Application

Problem

You want to find the slowest parts of your application, and speed them up.

Solution

Include the Ruby profiler in your application with include 'profile' and the profiler will start tracking and timing every subsequent method call. When the application exits, the profiler will print a report to your program's standard error stream.

Here's a program that contains a performance flaw:

	#!/usr/bin/env ruby
	# sequence_counter.rb
	require 'profile'

	total = 0
	# Count the letter sequences containing an a, b, or c.
	('a'..'zz').each do |seq|
	  ['a', 'b', 'c'].each do |i|
	    if seq.index(i)
	      total += 1
	      break
	    end
	  end
	end
	puts "Total: #{total}"

When the program is run, the profiler shows the parts of the program that are most important to optimize:

	$ ruby sequence_counter.rb
	Total: 150
	  %    cumulative   self               self      total
	 time    seconds   seconds    calls   ms/call   ms/call  name
	 54.55      0.30      0.30      702      0.43      0.50  Array#each
	 32.73      0.48      0.18        1    180.00    550.00  Range#each
	  7.27      0.52      0.04     1952      0.02      0.02  String#index
	  3.64      0.54      0.02      702      0.03      0.03  String#succ
	  1.82      0.55      0.01      150      0.07      0.07  Fixnum#+
	…

The program takes about 0.3 seconds to run, and most of that is spent in Array#each. What if we replaced that code with an equivalent regular expression?

	#!/usr/bin/env ruby
	# sequence_counter2.rb
	require 'profile'

	total = 0
	# Count the letter sequences containing an a, b, or c.
	('a'..'zz').each {|seq| total +=1 if seq =~ /[abc]/ }
	puts "Total: #{total}"

Running this program yields a much better result: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required