Define two variables, clocktickstart and clocktickend, of the clock_t data type, as they will be used to represent the processor time. The main idea of this program is to ascertain the time consumed during the execution of a function.
The clock function is invoked to know the number of clock ticks elapsed from the time the program is invoked. Assign the number of clock ticks returned to a clocktickstart variable. Then, invoke a somefunction() function, which includes a nested for loop. The idea of using nested loops is just to make the CPU invest some time in executing these loops. After the somefunction function is over, invoke the clock() function, and assign the number of clock ticks elapsed from the time the program is invoked to the clocktickend variable. The difference between the clocktickend and clocktickstart variables will give us the number of clock ticks used in executing the somefunction function. The number of clock ticks is then divided by CLOCKS_PER_SEC to distinguish the number of CPU seconds used to execute the function. Finally, the number of clock ticks used in executing the somefunction function and the CPU seconds used by it are displayed on the screen.
The program is compiled using GCC, as shown in the following screenshot. Because no error appears during compilation, the timecalc.c program is successfully compiled into a .exe file: timecalc.exe. Upon executing this file, the number of clock ticks and the number of CPU seconds required in the execution of the specific function in the program are displayed on the screen as follows:
Now, let's move on to the next recipe!