clock() — Determine processor time
Standards
Standards / Extensions | C or C++ | Dependencies |
---|---|---|
ISO C
POSIX.1 XPG4 XPG4.2 C99 Single UNIX Specification, Version 3 |
both |
Format
#include <time.h>
clock_t clock(void);
General description
Approximates the processor
time used by the program, since the beginning of an implementation-defined
time period that is related to the program invocation. To measure
the time spent in a program, call the clock() function at the start
of the program, and subtract its returned value from the value returned
by subsequent calls to clock(). Then, to obtain the time in seconds,
divide the value returned by clock() by CLOCKS_PER_SEC
.
If you use the system() function in your program, do not rely on clock() for program timing, because calls to system() may reset the clock.
In a multithread POSIX C application, if you are creating threads with a function that is based on a POSIX.4a draft standard, the clock() function is thread-scoped.
Returned value
If the time is available and can be represented, clock() returns the calculated time.
If unsuccessful, clock() returns (clock_t)-1. clock() may return -1 when running with STIMER REAL TQE present on MVS™/ESA Version 3 Release 1 Modification 2 (or earlier) system.
#pragma map ( clock(), "@@OCLCK")
Because of this pragma, when your application executes, it will attempt to access an XPG4 version of clock() which returns a clock_t value in units of 1000000 CLOCKS_PER_SEC. The XPG4 version of clock() is only available if POSIX(ON) is specified for execution of your application.
If _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
are defined when you compile your program AND your application is
run with POSIX(OFF), clock() will return (clock_t)-1
.
If neither _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED are defined when you compile your application, the historical C/370 value of CLOCKS_PER_SEC will be used and clock() calls in your application will be mapped to the historical C/370 version of clock() which returns a clock_t value in historical C/370 CLOCKS_PER_SEC units whether your application executes with POSIX(ON) or POSIX(OFF).
Example
/* This example prints the time elapsed since the program was invoked. */
#include <time.h>
#include <stdio.h>
double time1, timedif; /* use doubles to show small values */
int main(void)
{
time1 = (double) clock(); /* get initial time */
time1 = time1 / CLOCKS_PER_SEC; /* in seconds */
⋮
/* call clock a second time */
timedif = ( ((double) clock()) / CLOCKS_PER_SEC) - time1;
printf("The elapsed time is %f seconds\n", timedif);
}