Follow these steps to find out the number of clock ticks and CPU seconds required to run a function:
- Define two variables of the clock_t data type for saving processor time.
- Invoke the clock() function to discern the number of clock ticks elapsed from the time the program is invoked. The clock ticks are saved in one of the variables.
- Invoke a function whose processing time has to be established.
- Again, invoke the clock() function and then save the returned number of clock ticks to another variable.
- Subtract the number of clock ticks in the two variables to discern the number of clock ticks required to execute the function.
- Divide the number of clock ticks returned in the preceding steps by CLOCKS_PER_SEC to identify the number of seconds used by the function.
- Both the number of clock ticks and the CPU seconds required to execute the function are displayed on the screen.
The program for knowing the number of clock ticks and CPU seconds required in executing a function is as follows (timecalc.c):
#include <time.h>
#include <stdio.h>
void somefunction()
{
for (int i=0; i<32000; i++)
{
for (int j=0; j<32000; j++) ;
}
}
int main()
{
clock_t clocktickstart, clocktickend;
double timeconsumed;
clocktickstart = clock();
somefunction();
clocktickend = clock();
timeconsumed = (double)(clocktickend - clocktickstart) /
CLOCKS_PER_SEC;
printf("Number of clocks ticks required in running the function is
: %.3f\n", (double)(clocktickend - clocktickstart));
printf("Time taken by program is : %.2f sec\n", timeconsumed);
return 0;
}
Now, let's go behind the scenes to understand the code better.