Performance and profiling

Measure before you change

Perl is fast enough for most jobs, and guesses about hot spots are usually wrong. Start with a timer around the part that feels slow, and only then decide what to rewrite.

use Time::HiRes qw(time); my $start = time; my $lines = parse_log($file); printf "parsed %d lines in %.3f s\n", scalar @$lines, time - $start;

Time::HiRes gives sub-second resolution; the built-in time only counts whole seconds, which is useless for a function that takes 80 milliseconds. For a whole program, the shell already measures it:

time perl analyze.pl access.log

real 0m4.812s
user 0m4.601s
sys 0m0.204s

Real time includes waiting for disk and network; user time is the CPU your code burned. If user and real are close, the program is CPU-bound and code changes will help. If real is much larger, look at input and output first.

Benchmark

When two implementations look equally reasonable, race them instead of arguing. Benchmark runs each variant for a fixed time and prints a comparison table:

use Benchmark qw(cmpthese); my $text = "the quick brown fox jumps over the lazy dog. " x 2000; cmpthese(-1, { regex => sub { my $n = () = $text =~ /quick/g }, index => sub { my ($n, $pos) = (0, 0); while (($pos = index($text, "quick", $pos)) >= 0) { $n++; $pos++; } }, });

Rate regex index
regex 1948/s -- -32%
index 2859/s 47% --

The literal search wins because it never runs the regex engine. That does not mean every regex should become an index loop: the regex version is shorter and handles patterns that index cannot. Measure the real input before choosing.

The rates above are one run on one machine, and they move by a few percent between runs; the order is the part to read.

The first run of a benchmark is always slower because of warm-up, and a busy machine adds noise. Run it twice, and ignore differences under ten percent: they are usually measurement error, not a real win.

Profile with NYTProf

A benchmark tells you which snippet is faster. A profiler tells you which part of your program is slow, including the calls you did not suspect. Devel::NYTProf is the standard choice.

cpanm Devel::NYTProf

perl -d:NYTProf bin/report.pl access.log

The run writes nytprof.out. Converting it to HTML gives a report with time per subroutine, per line, and per call site:

nytprofhtml --open

Read the report from the top: the subroutine list shows where the time went, and the line view shows which statement inside it is hot. A line called a million times for one microsecond each is a different problem from one call that takes ten seconds.

Profiling adds overhead, so measure a smaller input if the full run takes minutes. The proportions usually survive the reduction, and the hot path is the same.

The usual wins

Most slow Perl scripts are slow for one of a few reasons, and none of them is the interpreter:

my $re = qr/^\d{4}-\d{2}-\d{2}$/; # compiled once my %seen = map { $_ => 1 } @ids; # lookup later is O(1)

Use index($haystack, $needle) >= 0 instead of a regex when you search for a literal string. Use Devel::Size::total_size when memory is the limit and you need to know which structure is huge.

Finally, treat readability as a feature. A ten percent speedup that makes the code unmaintainable is a bad trade unless the program runs on every request of a busy service. Measure, fix the hot spot, measure again, and stop when it is fast enough.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why does the lesson use Time::HiRes instead of the built-in time?

    Answer

    It has sub-second resolution, which a whole-second clock cannot give a fast function

    The built-in clock counts whole seconds, so a function that takes 80 milliseconds measures as zero.

  2. What does cmpthese do?

    Answer

    It runs each variant for a fixed time and prints a comparison table

    The module races the snippets and reports the rate and the relative difference, which settles an argument that guesses cannot.

  3. What does the user time of a shell time report tell you?

    Answer

    The CPU time your code burned

    Real time includes waiting for disk and network, so a small gap between user and real means the program is CPU-bound.

  4. What does a profiler give you that a benchmark does not?

    Answer

    Which part of the program is slow, including calls you did not suspect

    The benchmark compares pieces you already chose, while the profiler finds the piece you would not have picked.

  5. Why compile a regex with qr// once instead of writing the pattern inside a loop?

    Answer

    The compiled pattern is reused instead of built again on every pass

    A literal pattern in a loop is compiled again on each pass, and the qr object is compiled once.

  6. What does this program print? my $text = "one two one two one"; my $n = () = $text =~ /one/g; print $n, "\n";

    Answer

    3

    The global match in list context returns one match per occurrence, and the list assignment counts them.

  7. What does this program print? my @ids = (1 .. 10); my %seen = map { $_ => 1 } @ids; print exists $seen{9} ? "found\n" : "missing\n";

    Answer

    found

    The hash built once turns the lookup into a constant-time check, and 9 is one of the ids.

  8. What does this program print? my ($text, $n, $pos) = ("one two one", 0, 0); while (($pos = index($text, "one", $pos)) >= 0) { $n++; $pos++; } print $n, "\n";

    Answer

    2

    The loop finds the literal twice, which is the hand-written version of the regex count.

  9. What does this program print? my @words = qw(ccc a bb); my @sorted = map { $_->[1] } sort { $a->[0] <=> $b->[0] } map { [length $_, $_] } @words; print join(" ", @sorted), "\n";

    Answer

    a bb ccc

    The transform computes each length once and sorts the pairs, which is the Schwartzian transform.

  10. What does this program print? my @ids = (1, 2, 2, 3); my %seen = map { $_ => 1 } @ids; print scalar keys %seen, "\n";

    Answer

    3

    The hash keeps one entry per distinct id, so the two 2s collapse into one key.

Article author: Arthur Isaev