Bird
Raised Fist0
CHow-ToBeginner · 3 min read

How to Use clock() Function in C for Measuring Time

In C, use the clock() function from time.h to measure CPU time consumed by your program. It returns the processor time used since the program started as a clock_t value, which you convert to seconds by dividing by CLOCKS_PER_SEC.
📐

Syntax

The clock() function is declared in the time.h header. It returns a clock_t value representing the processor time used by the program since it started.

To get the time in seconds, divide the returned value by the constant CLOCKS_PER_SEC.

c
#include <time.h>

clock_t clock(void);
💻

Example

This example shows how to measure the time taken by a simple loop using clock(). It calculates the elapsed CPU time in seconds.

c
#include <stdio.h>
#include <time.h>

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

    start = clock();

    // Simple loop to waste some CPU time
    for (long i = 0; i < 100000000; i++) {
        // do nothing
    }

    end = clock();

    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

    printf("CPU time used: %f seconds\n", cpu_time_used);

    return 0;
}
Output
CPU time used: 0.400000 seconds
⚠️

Common Pitfalls

  • Not including time.h will cause compilation errors.
  • Dividing the clock() result by a wrong value instead of CLOCKS_PER_SEC leads to incorrect time.
  • Using clock() to measure real elapsed (wall) time is not reliable; it measures CPU time used by the program.
  • On some systems, clock() may return (clock_t)-1 if the processor time is not available.
c
#include <stdio.h>
#include <time.h>

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

    start = clock();

    // Some code

    end = clock();

    // Wrong: dividing by 1000 instead of CLOCKS_PER_SEC
    cpu_time_used = ((double) (end - start)) / 1000;

    printf("Wrong CPU time used: %f seconds\n", cpu_time_used);

    // Correct:
    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
    printf("Correct CPU time used: %f seconds\n", cpu_time_used);

    return 0;
}
Output
Wrong CPU time used: 0.000400 seconds Correct CPU time used: 0.000004 seconds
📊

Quick Reference

TermDescription
clock()Returns processor time used since program start as clock_t
clock_tData type to store processor time values
CLOCKS_PER_SECConstant to convert clock_t units to seconds
time.hHeader file where clock() and related constants are declared
✅

Key Takeaways

Use clock() to measure CPU time used by your program, not real elapsed time.
Always divide the difference of clock() values by CLOCKS_PER_SEC to get seconds.
Include time.h to use clock() and related constants.
Check for clock() returning (clock_t)-1 which means the processor time is not available.
For measuring real elapsed time, consider other functions like time() or platform-specific timers.