9.3. Profiling

When working on a program, it is tempting to think about making it as fast as you possibly can. You might try to avoid an addition here or a test there.

But doing that probably saves very little. It is not worth the added potential for making mistakes to save a microsecond. So temper your desire for the utmost speed. The most important thing is for your software to work.

One easy way to significantly speed up your program is simply ask the compiler to run its optimizer. That can readily speed up your program by a factor of 2.

But if you find that your program is too slow, do what experts do. Run a profiler. A profiler takes statistics while a program runs. Then it tells you where the program spent its time. Typically, you find that it spends the vast majority of its time running a small amount of the program. You could find, for example, that it spends 70% of its time running 5% of the code. If you want to speed up the program, work on that 5% of the code.

Linux provides a simple profiler called prof. Run

  prof command
to run a command and have prof take statistics. It writes a file called prof.out. Another profiler, gprof, is similar but provides far more details about what the program did. Run
  man prof
or
  man gprof
to see manual pages.