Recursive C Functions 199
function coefficient
f(n-1) 1 f(2)
f(n-2) 2 f(3)
f(n-3) 3 f(4)
f(n-4) 5 f(5)
f(n-5) 8 f(6)
f(n-6) 13 f(7)
TABLE 13.2: Coefficients for computing f (n).
Does this mean recursion is bad? Does this mean that recursion is slow? Why should we
even bother to learn recursion? The problem is not recursion, but the example. We cannot
generalize from a bad example to say that recursion is slow. Recursion can be used to good
advantage in some time-critical applications. If you have a nail and a knife, you will find
that hitting the nail with a knife is difficult. Does this mean a knife is bad? If you need to
hit a nail, you need a hammer. A knife is a bad tool for hitting a nail. If you want to cut
paper, a knife is better than a hammer. If you have a bolt, you need a wrench. A hammer
is not better than a wrench and a wrench is not better than a hammer. They are different.
One is better than the other in some scenarios. If a book tells you a hammer is better
than a wrench, you will say, “This doesn’t make sense. In some cases, a wrench is better.”
You cannot generalize this example and conclude that recursion is slower. Some books do
not explain that this particular top-down method is slower than this bottom-up method.
As a result some students mistakenly think recursion is slow by generalizing this example.
Some other books explain that this top-down method is slower than this bottom-up method
without further explanation. These books give students the strong impression that recursion
is slow. The truth is that recursion is a good approach for some problems, not all.
13.7 Performance Profiling with gprof
Many studies on software performance find that performance is generally dominated
by just a few factors. This is true for both simple and complex systems. A general rule of
thumb is “10% of the code consumes 90% of the time”. Improving the correct 10% of code
will have a noticeable impact on performance. Conversely, improving the other 90% of code
will have negligible impact. The question is how to find the 10% of interest. Guessing is not
a good approach. Even experienced programmers find it very hard to predict which parts
of a complex program cause performance bottlenecks.
Experienced programmers know that tools can help identify that 10% of the code. A
tool called gprof is designed specifically for this purpose. To use gprof, add -pg after gcc
and execute the program as usual. For example:
$ gcc -Wall -Wshadow -pg fib.c fib1.c fib2.c -o fibprog
Consider the Fibonacci functions referenced earlier. After running the program, a special
file called gmon.out is generated. This file stores the profiling information for running the
program and it is not readable using a text editor. Please use the gprof program to view
the content in gmon.out. The command is: