Measuring Program Execution Time with Stopwatch(C++) - Stopwatch(C++)

Measuring Program Execution Time with Stopwatch(C++) - Stopwatch(C++)

During the ``performance tuning'' phase of development, programmers measure program execution time. They may measure the execution time of an entire program (using the time(1) command) or only parts of a program; for example, they may measure the time spent in a critical loop or subroutine. Three kinds of execution time are of interest: user time (the CPU time spent executing the user's code); system time (the CPU time spent by the operating system on behalf of the user's code); and occasionally real time (elapsed, or ``wall clock'' time).

The standard UNIX® operating system facilities used for making such measurements are described in times(2). The following C program illustrates their use:

       #include <stdio.h>
       #include <sys/param.h>
       #include <sys/times.h>
       #include <sys/types.h>
       #define N 10000
           int i;
           struct tms t,u;
           long r1,r2;
           r1 = times(&t);
               computation of interest        }
           r2 = times(&u);
           printf("user time=%f\ n",
           printf("system time=%f\ n",
           printf("real time=%f\ n",

The type struct tms is defined in sys/times.h:

       struct tms{
           time_t tms_utime;
           time_t tms_stime;
           time_t tms_cutime;
           time_t tms_ustime;

Calling times() with a struct tms reads the system clock and assigns values to the structure members. These values are reported in units of clock ticks; they must be divided by the clock rate (the number of ticks per second, HZ, a system-dependent constant defined in sys/param.h) to convert to seconds. Moreover, the values reported are the number of ticks which occurred since some arbitrary point in the past; it is therefore necessary to call times() twice in and take a difference.

If this procedure sounds confusing, it is. And as you can see from the example, the resulting code can be hard to write, read and modify. The standard facilities, although powerful, portable, and completely general, are not at the appropriate level of abstraction for expressing notions of execution time measurement in a clear and comprehensible fashion.

This tutorial introduces a C++ component called Stopwatch(C++) which provides a natural, easy-to-use interface to the standard system facilities.

Next topic: The Stopwatch Analogy

© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 02 June 2005