Course contentsShow
← C
Lesson 1184 of 1,21916. Practice and ProjectsFree lesson

Understanding CPU cycles vs. Wall time

Understanding CPU cycles vs. Wall time

What you'll learn: You will learn to distinguish between the actual time a human waits for a program to finish and the internal computational effort the processor exerts.

The Stopclock vs. The Treadmill

When profiling C code, beginners often rely on "Wall Time." This is the time measured by the clock on your wall. If you start a function at 12:00:00 and it finishes at 12:00:05, the wall time is five seconds.

However, your CPU doesn't think in seconds; it thinks in cycles. Imagine a person on a treadmill. The "Wall Time" is how long they are in the gym. The "CPU Cycles" are how many actual steps they took. If the person stops to tie their shoes or chats with a friend, the clock keeps ticking (Wall Time increases), but they aren't taking steps (CPU Cycles stay the same).

Why the difference matters

In C, your program often competes with other processes. If you measure a function and it takes 10ms, it might be because the code is slow, or it might be because the Operating System paused your program to check for a Wi-Fi signal.

  • Wall Time (Real Time): Includes waiting for disk I/O, network responses, or other programs.
  • CPU Time (Cycles): Measures only the time the processor was actively executing your code's instructions.

Measuring in C

The standard library provides clock(), which helps track processor time rather than the wall clock.

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

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

    start = clock();
    
    // Perform a heavy computation
    long sum = 0;
    for (long i = 0; i < 100000000; i++) {
        sum += i;
    }

    end = clock();

    // Convert clock cycles to seconds
    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

    printf("Computation took %f seconds of CPU time\n", cpu_time_used);
    return 0;
}

If you put a sleep(5) command in the middle of that code, the Wall Time would increase by five seconds, but the cpu_time_used would remain almost exactly the same. When optimizing C, you usually want to reduce CPU cycles to make your logic more efficient, regardless of what else is happening on the computer.

Key takeaway

Wall time is what the user experiences, but CPU cycles are the true measure of your code's computational efficiency.