Programming pearls: profilers

A physician doesn't feel dressed without a stethoscope, and a true electrical engineer is never far from an oscilloscope. Both professionals know that they need tools for studying the objects they manipulate. What tools do you use to study your programs? Sophisticated analysis systems are now widely available, ranging from interactive debuggers to systems for program animation. But just as CAT scanners will never replace stethoscopes, complex software will never replace the simplest tool we programmers have for looking inside our programs: profilers. This column starts by using two kinds of profilers to speed up a tiny program. The next sections sketch various uses of profilers and a profiler for a nonprocedural language. The final section discusses building profilers. Computing Primes In this section we'll start with a straightforward program for computing prime numbers and use profilers to decrease its run time. Although we'll pretend that our goal is to make a program faster, keep in mind that the real purpose of this section is to illustrate profilers. Program Pl is a C program' to print all primes less than 1000, in order. The prime function returns 1 (true) if its integer argument II is prime and 0 otherwise ; it tests all integers between 2 and n-1 to see whether they divide n. The main procedure uses that routine to examine the integers 2 through 1000, in order, and prints primes as they are found. I wrote Program Pl as I would write any program, and then compiled it with a profiling option. After the program executed, a single command generated the listing shown. (I have made minor formatting changes to a few of the outputs in this column.) The numbers to the left of each line tell how many times the line was executed. They show, for instance, that main was called once, it tested 999 integers, and found 168 primes. Function prime was called 999 times; it returned one 168 times and returned zero the other 831 times (a reassuring quick check: 168 + 831 = 999). It tested a total of 78,022 potential factors, or about 78 factors for each number examined for primality. ' A few C-isms: The statement I++ increments the integer 1. The loop for (i=2 ; i<= n ; i++) iterates i from 2 to n. The statement a=b assigns the value of b to a; the expression a==b is true if …

[1]  Donald E. Knuth,et al.  An empirical study of FORTRAN programs , 1971, Softw. Pract. Exp..