The clock()
function in C language is defined in the <time.h>
header file. clock()
does not accept parameters and returns the number of clock ticks passed since the program is executed.
The function is defined in C <time.h>
header file as:
clock_t clock(void)
Below is an example of how one can use the clock()
function by:
#include <time.h>#include <stdio.h>int main(){clock_t start_time,end_time;int i;start_time = clock();printf("Time when program is started: %ld\n", start_time);printf("Running a program loop for testing");for(i=0; i< 1000; i++){}end_time = clock();printf("End of the program: %ld\n", end_time);printf("Total time of the program: %ld\n", end_time-start_time);return(0);}
The ticks elapsed since the program’s run begins can vary from one machine to another, which can depend on many factors such as the operating system, device used, and how resources are allocated to the system by the operating system.
For an operating system that is running multiple processes simultaneously, the ticks may elapse slower than for one running multi-threaded programs.
Furthermore, if you want to convert the return value of the clock()
function to the number of seconds that have elapsed, then you must divide the value by CLOCKS_PER_SEC
, which is defined in the <time.h>
header file.
CLOCKS_PER_SEC is a macro that varies for every operating system and keeps a count of the number of ticks elapsed per second.
Provided below is an example of how to divide variables by CLOCKS_PER_SEC
:
#include <time.h>#include <stdio.h>int main(){clock_t start_time,end_time;int i;start_time = clock();printf("Time when program is started: %ld seconds \n", (start_time/CLOCKS_PER_SEC));printf("Running a program loop for testing \n");for(i=0; i< 1000000000; i++){}end_time = clock();printf("End of the program: %ldseconds \n", end_time/CLOCKS_PER_SEC);printf("Total time of the program: %ld seconds \n", (end_time-start_time)/CLOCKS_PER_SEC);return(0);}
Free Resources