|
|
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 main(){ int i; struct tms t,u; long r1,r2; r1 = times(&t); for(i=0;i<N;i++){ computation of interest } r2 = times(&u); printf("user time=%f\ n", ((float)(u.tms_utime-t.tms_utime))/(N*HZ)); printf("system time=%f\ n", ((float)(u.tms_stime-t.tms_stime))/(N*HZ)); printf("real time=%f\ n", ((float)(r2-r1))/(N*HZ)); }
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.