Speeding up
Your Perl Programs
Randal L. Schwartz
How fast does your Perl run? I hope that, most of the time, the answer is
"fast enough". But sometimes it may not be. How do we speed up a Perl program?
How do we know what's making it unacceptably slow?
The first rule of speed optimization is "don't". Certainly, don't write things
that waste time, but first aim for clarity and maintainability. With today's
processor speeds far exceeding the "supercomputers" of yesterday, sometimes
that's "fast enough".
But how do we know whether something is "fast enough"? The first easy cut
is just to check total run time. That's usually as simple as putting "time"
in front of your program invocation, and looking at the result (which may vary
depending on your operating system and choice of shell). For example, here's
a run of one of my frequently invoked programs, preceding the command (get.mini)
with time:
[localhost:~] merlyn% time get.mini
authors/01mailrc.txt.gz ... up to date
modules/02packages.details.txt.gz ... up to date
modules/03modlist.data.gz ... up to date
67.540u 3.290s 1:40.62 70.3% 0+0k 1585+566io 0pf+0w
So, this tells me that this program took about 70 CPU seconds over a 100-second
timespan, essentially doing nothing useful for me except verifying that my local
mirror of the CPAN is up to date. (Generally, to get sensible numbers, I have
to do this on an otherwise idle system.)
Hmm. I wonder where it's actually spending all of its time? I can get the
next level of information by invoking the built-in Perl profiler on the script.
Simply include -d:DProf as a Perl command switch, and Perl will automatically
record where the program is spending its time in a file called tmon.o
|