clock() — Determine Processor Time

Format

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

Language Level: ANSI

Threadsafe: Yes.

Description

The clock() function returns an approximation of the processor time used by the program since the beginning of an implementation-defined time-period that is related to the process invocation. To obtain the time in seconds, divide the value that is returned by clock() by the value of the macro CLOCKS_PER_SEC.

Return Value

If the value of the processor time is not available or cannot be represented, the clock() function returns the value (clock_t)-1.

To measure the time spent in a program, call clock() at the start of the program, and subtract its return value from the value returned by subsequent calls to clock(). On other platforms, you can not always rely on the clock() function because calls to the system() function might reset the clock.

Example that uses clock()

This example prints the time that has elapsed since the program was called.

#include <time.h>
#include <stdio.h>
 
double time1, timedif;        /* use doubles to show small values */
 
int main(void)
{
    int  i;
 
    time1 = (double) clock();            /* get initial time */
    time1 = time1 / CLOCKS_PER_SEC;      /*    in seconds    */
 
    /* running the FOR loop 10000 times */
    for (i=0; i<10000; i++);
 
    /* call clock a second time */
    timedif = ( ((double) clock()) / CLOCKS_PER_SEC) - time1;
    printf("The elapsed time is %lf seconds\n", timedif);
}

Related Information



[ Top of Page | Previous Page | Next Page | Contents | Index ]