What is clock_t in C?

clock_t is a typedef of long int and is defined in the time.h header. It is used to store the processor time in terms of the number of CPU cycles passed since the start of the process.

To convert the number of CPU clock cycles into seconds, we need to use the CLOCKS_PER_SEC constant, which is also defined in the time.h header.

The function clock() defined in the time.h header returns the number of elapsed CPU clock cycles.

Parameters

N/A

Return type

The return type of clock() is clock_t because the function returns the number of CPU cycles elapsed since the start of the process.

Example

#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
int main(){
clock_t start, end, duration;
start = clock();
for(int i=0; i<6000000; i++){
log(100);
}
end = clock();
duration = (end - start);
printf("Processor cycles taken : %f cycles\n", (float)duration);
printf("Processor time taken : %f seconds\n", (float)duration/CLOCKS_PER_SEC);
return 0;
}

In the above code, we are logging the CPU cycles before and after the loop in the start and end variables. These variables, are of clock_t type and store the number of CPU cycles passed.

Now, we can print out the CPU time and number of CPU cycles since the beginning of the program.

Note: to print out the time in seconds, we have to divide the duration with CLOCKS_PER_SEC

It will convert the number of CPU cycles to the CPU time taken by the process as shown in the following code:

float time_in_sec = (float) (duration) / CLOCKS_PER_SEC

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved