The clock() function returns the approximate processor time consumed by a program, measured in clock ticks. The elapsed clock ticks can be converted into seconds using the CLOCKS_PER_SEC constant.
- The clock() value depends on how the operating system allocates CPU resources to the program.
- The difference between two clock() values gives the clock ticks used during that execution period.
#include <math.h>
#include <stdio.h>
#include <time.h>
int main()
{
float a;
clock_t time_req;
// Without using pow function
time_req = clock();
for (int i = 0; i < 200000; i++) {
a = log(i * i * i * i);
}
time_req = clock() - time_req;
printf("Processor time taken for multiplication: %f "
"seconds\n",
(float)time_req / CLOCKS_PER_SEC);
// Using pow function
time_req = clock();
for (int i = 0; i < 200000; i++) {
a = log(pow(i, 4));
}
time_req = clock() - time_req;
printf("Processor time taken in pow function: %f "
"seconds\n",
(float)time_req / CLOCKS_PER_SEC);
return 0;
}
Output
Processor time taken for multiplication: 0.002006 seconds Processor time taken in pow function: 0.004998 seconds
Syntax
clock_t clock( void );
Parameters
- This function does not accept any parameter.
Return Value
- This function returns the approximate processor time that is consumed by the program.
- This function returns -1 in case of failure.