Profile with Devel::NYTProf

Profile before you decide where to optimize—you might be surprised where you’re losing all of your performance.

We won’t go into all the details of profiling in this Item, but you can read about those in Mastering Perl. In short, profilers count something then report the results. They can track any of the things that you might care about. The Devel::NYTProf module, like most profilers, tracks time, counting the statements you run and how long they take.

Basic profiling

Perl profilers are really debuggers, using the internal hooks to detect movement in and out of statements. As such, you can load it with the -d switch just like any other debugger:

% perl -d:NYTProf some_program

You can also load it as a module and NYTProf will figure it out:

% perl -MDevel::NYTProf some_program

Either way, you can set the NYTProf environment variable to specify various settings (which you’ll have to read the documentation). For instance, to start profiling after the compilation phase, you use the start field:

% export NYTPROF=start=init
% perl -MDevel::NYTProf some_program

That’s it. Your program will run slower as NYTProf watches it and records that data, so don’t worry about the wallclock time. If your program is already agonizingly slow, it’s going to seem worse. Perhaps not a lot worse, but you’ll probably notice the difference. Maybe it’s time to get a cup of coffee.

The reports

NYTProf stores its data in the ./nytprof.out file (although you can change that). That’s just the data, though. To look at it, you need to convert it to a particular format. The distribution comes with several programs to do that already. The easiest and most popular might be HTML:

% nytprofhtml
Reading nytprof.out
Processing nytprof.out data
Writing sub reports to nytprof directory
 100% ... 
Writing block reports to nytprof directory
 100% ... 
Writing line reports to nytprof directory
 100% ... 

Inside the nytprof/ directory, you’ll find index.html, which presents the summary of the profile:

Here’s a full profile from the a run of the cpan command.

Call graphs

NYTProf also generates call graphs that you can inspect with Graphviz.