Chapter 4. Profiling Perl
Before I can do anything to improve my programs, I have to make a decision about what I am going to fix. Before I spend the time to do that, I want to figure out what I should focus on. How do I get the most improvement for the least amount of fiddling? What should I work on first? Through the process of profiling, by which I record and summarize what a program is doing, I can make those decisions. Luckily, Perl already offers several tools to do this.
Finding the Culprit
I want to compute a factorial. It’s the old saw of performance discussions, and I’ll get to something more interesting in a moment. When I searched for “factorial subroutines,” almost every implementation (aside from those in assembly language) was a recursive algorithm, meaning that the subroutine figured out part of the problem, then called itself with a subproblem, and kept doing that until there were no more subproblems, eventually working its way up to the original call. Here’s how I’d write that in Perl:
#!/usr/bin/perl
# factorial_recurse.pl
sub factorial {
return unless int( $_[0] ) == $_[0];
return 1 if $_[0] == 1;
return $_[0] * factorial( $_[0] - 1 );
}
print factorial( $ARGV[0] ), "\n";Now I want to figure out how to improve this toy program. It’s
already pretty fast because Perl can’t really count that high. With
anything over 170, my program on my machine returns Inf (more on that in a moment). Despite that,
I’ll profile it anyway. I use the Devel::SmallProf module to get a ...