Main Navigation

Content

Optimising and Profiling Perl Code

Learn Perl Now!
And get a job doing Perl.

Introduction

Before you try to make your code run faster, you should first make sure that it is too slow for your needs. After all, spending time profiling and optimising an already performant code will not yield any benefits for production. So benchmark your code, see how well it performs, and then continue reading this page if it is indeed too slow. As a corollary, when writing code, always make sure you optimise for clarity and correctness first, not for speed.

The first steps in optimising a code that is too slow are benchmarking and profiling it, in order to see which parts of the code consume the most time.

Benchmarking

Benchmark - a module for Benchmarking

The Benchmark.pm module which is maintained as part of the Perl 5 core modules can be used for benchmarking different codes for performance.

Profiling

Devel-NYTProf

Devel-NYTProf is a very powerful profiling framework for Perl that leaves all the previous attempts at providing a Perl profiler way behind. Use it to determine where your Perl code spends most of its time.

How to Optimise

Here are some collected resources about optimisation:

  1. Shlomi Fish has written an essay titled "Optimizing Code for Speed" (a somewhat more up-to-date version is available on the English Wikibooks site).

  2. Jon Bentley's out-of-print book "Writing Efficient Programs" is a previous treatment of the subject.

  3. "Shavin' Another Second" is a blog post by Shlomi Fish about how he optimised some Perl code of his.

Use a database

If your program is not using a database of some sort, then converting it to use one may yield a substantial speed improvement. See our page about using databases with Perl for more information.

Optimise by Writing Code in a Faster Language

If all else fails, then re-implementing the slow code in a faster language such as C or C++ and embedding it inside Perl is an option. Here are some alternatives for writing extensions to Perl in C and other languages that are compiled to machine code:

  1. XS - XS is the original way to bind code in C or similar languages to Perl, and is still popular. However, it is difficult to perform correctly, and you may wish to look at the alternatives below.

  2. Inline::C - Inline::C provides a somewhat easier way to create Perl bindings to C subroutines. There are other Inline modules on CPAN.

  3. SWIG - SWIG is the so-called "Simplified Wrapper and Interface Generator" and allows to create bindings to Perl and many other languages from a common source.

  4. perl-ctypes - this is a port of Python's ctypes package, that will eventually allow invoking the subroutines of dynamically-loaded libraries from Perl at run-time.

Share/Bookmark

Sidebar

Footer