Timing on your computer

In order to determine the relative execution efficiency of various algorithms, you will need to use a timer package.  I have available (see below) for your use such a package written in C.  However, with advance approval from me, you may use other packages. Note that CPU time is used by your program (user time) as well as the system (system time). We will be interested in capturing the values of the user time usage only.

A problem:  On some systems, the timing function gives times in multiples of .01 seconds.  On others, the timing coarseness may be significantly smaller or larger.  (You should determine the timing coarseness for your machine.)  Thus, for example, on a system with .01 second timing coarseness, timing anything which takes less than one fiftieth of a second could result in more than a 50% error.  Your programs, for small values of n, should be easily this fast.

A solution:  When the algorithm to be timed is too fast to obtain an accurate measurement, the algorithm can be run many times in succession, with the cumulative time being measured.  This time can then be divided by the number of runs to obtain a more accurate measurement of the time required by an individual run.  As little as possible, other then the successive calls, should occur while the timing is taking place.  In fact, for particularly speedy code, the time spent updating the loop variable may be of the same order of magnitude as the time you are attempting to measure.  To account for this, you can subsequently time the loop with a (nearly) empty body and subtract this measure from your first measure, the net result reflecting more accurately the time spent within the code of interest. One should note that some optimizing compilers will optimize loops that contain an empty body by discarding them.

Timer package

Program file timer.c should be compiled and linked with your program system.  It defines the following routines:

Header file timer.h declares the routines that are defined in timer.c and it should be included in all program files that invoke any of those routines.


Dan Hirschberg
Computer Science Department
University of California, Irvine, CA 92697-3435
dan (at) ics.uci.edu
Last modified: Dec 7, 2011