Previous Page
Next Page


Obtains the CPU time used by the process

#include <time.h>
clock_t clock( void );

If you want to know how much CPU time your program has used, call the clock( ) function. The function's return type, clock_t, is defined in time.h as long. If the function returns -1, then the CPU time is not available. Note that the value of clock( ) does not reflect actual elapsed time, as it doesn't include any time the system may have spent on other tasks.

The basic unit of CPU time, called a "tick," varies from one system to another. To convert the result of the clock( ) call into seconds, divide it by the constant CLOCKS_PER_SEC, which is also defined in time.h.


#include <stdio.h>
#include <time.h>
time_t start, stop;
clock_t ticks; long count;

int main( )
  for (count = 0; count <= 50000000; ++count)
    if (count % 1000000 != 0) continue;   /* measure only full millions */
    ticks = clock( );
    printf("Performed %ld million integer divisions; "
           "used %0.2f seconds of CPU time.\n",  count / 1000000,
  printf("Finished in about %.0f seconds.\n", difftime(stop, start));
  return 0;

This program produces 51 lines of output, ending with something like this:

Performed 50 million integer divisions; used 2.51 seconds of CPU time.
Finished in about 6 seconds.

See Also

time( ), difftime( )

Previous Page
Next Page