next up previous
Contents Next: Exercises Up: Recursion and Iteration Previous: Tail Recursion

Timing Function Calls

The Lisp interpreter provides a interesting feature for timing the evaluation of a function call. Any expression can be timed using (time <exp> ). For example, here's time applied to the recursive and iterative versions of power as evaluated by the interpreter:

> (time (power 2 100))
real time : 0.200 secs            ;; your output will vary
run time  : 0.133 secs
1267650600228229401496703205376

> (time (power-i 2 100))
real time : 0.200 secs
run time  : 0.083 secs
1267650600228229401496703205376
To assess the relative speeds of these two functions, run time (i.e. the amount of time required by the computer's central processing unit to perform the calculation) is the key figure. In this example, power-i uses about 2/3 as much cpu time as power.

Real time refers to the time it actually took the computer to return the answer to the screen. In this example, there is no difference in real time between the two functions. Run time and real time can differ because computers running multitasking operating systems, such as UNIX(tm), switch cpu time between different processes to give the appearance of running them simultaneously. If there are a lot of other processes running on the computer, the run time for the Lisp function is unchanged, but real time increases.



© Colin Allen & Maneesh Dhagat
March 2007