clock() Function Example in C Programming

In this source code example, we will see how to use the clock() function in C programming with an example.

clock() Function Overview

The clock() function in C returns the processor time used by the program since the program was launched. This is invaluable for performance measurements since it provides an approximation of the CPU time taken by the program to execute. The function is part of the time.h or ctime library. 

Key Points: 

- The time.h (or ctime in C++) header is needed to use clock()

- The function returns the processor time used by the program, which is expressed in clock ticks

- To convert the returned value to seconds, you divide by CLOCKS_PER_SEC (a defined constant in time.h). 

- While difftime() measures real time, clock() measures processor (or CPU) time.

Source Code Example

#include <stdio.h>
#include <time.h>  // Required for clock() and CLOCKS_PER_SEC

int main() {
    clock_t start, end;
    double cpu_time_used;

    start = clock();  // Start the timer

    // Simulating a delay or operation for this example
    for (long int i = 0; i < 10000000; i++);

    end = clock();  // End the timer

    // Compute the difference and convert to seconds
    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

    printf("The operation took %f CPU seconds.\n", cpu_time_used);

    return 0;
}

Output

The operation took X.XXXXXX CPU seconds.
(Note: The actual time X.XXXXXX will vary based on system performance and compiler optimizations.)

Explanation

1. The necessary header files are included: stdio.h for input/output functions and time.h for the clock() function and the CLOCKS_PER_SEC constant.

2. Within the main() function, the clock() function is first called to capture the starting time in clock ticks.

3. A loop is introduced to emulate a delay or an operation.

4. Once the operation is done, clock() is called again to capture the ending time.

5. To compute the CPU time used, the difference between the start and end times is divided by CLOCKS_PER_SEC.

6. Finally, the calculated CPU time in seconds is displayed.

The clock() function offers developers a practical tool to measure the efficiency of their code by assessing the CPU time required for execution. It's especially useful for optimizing performance-critical sections of a program.


Comments