Sunday, December 31, 2006

[Pages 163-5] But it's too slow ! - The profiler


Listen to this article.

Value: High

Level: Easy

Summary:

Ruby comes with a code profiler: it shows you the number of times each
method in the program is called and the average and cumulative time
that Ruby spends in those methods. You can add profiling to your code
using the command-line option "-r profile" or from within the code
using "require 'profile'".

The first thing to notice is that the timings shown are a lot slower
than when the program runs without the profiler. Profiling has a
serious overhead, but the assumption is that it applies across the
board, and therefore the relative numbers are still meaningful.

Memo: None

Example:
require 'profile'
count = 0
words = File.open("/usr/share/dict/words")
while word = words.gets
word = word.chomp!
if word.length == 12
count += 1
end
end
puts "#{count} twelve-character words"

# the following code runs more than five times faster
require 'profile'
words = File.read("/usr/share/dict/words")
count = words.scan(PATT= /^............\n/).size
puts "#{count} twelve-character words"

Reported errata (at 10/17/06 14:17:18 PDT): 1
*Erratum #4666 is a minor suggestion.

Errata I found: 0

My suggestions to the author: 0

Doubts: 1
*"Always try to eliminate unneeded code. Remember to check the code
without the profiler afterward, though—sometimes the slowdown the
profiler introduces can mask other problems.". What does it mean ?

0 Comments:

Post a Comment

<< Home