next up previous
Next: Random numbers Up: Scientific programming in C Previous: Command line parameters

Timing

The header file time.h defines a number of library functions which can be used to assess how much CPU time a C program consumes during execution. The simplest such function is called clock(). A call to this function, with no argument, will return the amount of CPU time used so far by the calling program. The time is returned in a special data type, clock_t, defined in time.h. This time must be divided by CLOCKS_PER_SEC, also defined in time.h, in order to covert it into seconds. The ability to measure how much CPU time a given code consumes is useful in scientific programming: e.g., because it allows the effectiveness of the various available compiler optimization flags to be determined. Optimization usually (but not always!) speeds up the execution of a program. However, over aggressive optimization can often slow a program down again.

The program listed below illustrates the simple use of the clock() function. The program compares the CPU time required to raise a double to the fourth power via a direct calculation and via a call to the pow() function. Actually, both operations are performed a million times and the elapsed CPU time is then divided by a million.

/* timing.c */
/* 
  Program to test operation of clock() function
*/

#include <time.h>
#include <math.h>
#define N_LOOP 1000000

int main()
{
  int i;
  double a = 11234567890123456.0, b;
  clock_t time_1, time_2;

  time_1 = clock();
  for (i = 0; i < N_LOOP; i++) b = a * a * a * a;
  time_2 = clock();
  printf ("CPU time needed to evaluate a*a*a*a:    %f microsecs\n",
          (double) (time_2 - time_1) / (double) CLOCKS_PER_SEC);

  time_1 = clock();
  for (i = 0; i < N_LOOP; i++) b = pow(a, 4.);
  time_2 = clock();
  printf ("CPU time needed to evaluate pow(a, 4.): %f microsecs\n",
          (double) (time_2 - time_1) / (double) CLOCKS_PER_SEC);

  return 0;
}
The typical output from this program is as follows:
 
CPU time needed to evaluate a*a*a*a:    0.190000 microsecs
CPU time needed to evaluate pow(a, 4.): 1.150000 microsecs
%
Clearly, evaluating a fourth power using the pow() function is a lot more expensive than the direct calculation. Hence, as has already been mentioned, the pow() function should not be used to raise floating point quantities to small integer powers.


next up previous
Next: Random numbers Up: Scientific programming in C Previous: Command line parameters
Richard Fitzpatrick 2006-03-29