Course contentsShow
← C
Lesson 896 of 1,21912. The Standard LibraryFree lesson

Measuring CPU ticks with `clock`

Measuring CPU ticks with clock

What you'll learn: How to use the clock() function to measure the amount of processing power your code consumes.

The Stopwatch for your Processor

When we want to know how long a program takes to run, we might reach for a wall clock. However, wall clocks are misleading in programming. Your computer is constantly multitasking—checking for emails, updating the clock, or moving the mouse cursor. If your program "sleeps" for two seconds, it hasn't actually done any work, yet a wall clock would say two seconds have passed.

In C, we use clock() from the <time.h> library to measure "CPU time." Think of this as a specialized stopwatch that only ticks when the processor is actually working on your specific instructions.

Ticks vs. Seconds

The clock() function returns a value of type clock_t. This isn't a measurement of seconds; it’s a count of processor ticks. Because different computers tick at different speeds, C provides a constant called CLOCKS_PER_SEC. To find the actual time in seconds, you divide your ticks by this constant.

Seeing it in action

To measure a specific block of code, you take a "snapshot" before it starts and another after it finishes.

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

int main() {
    // 1. Capture the start ticks
    clock_t start_time = clock();

    // 2. Perform a heavy task (a simple loop)
    double total = 0;
    for (int i = 0; i < 100000000; i++) {
        total += i;
    }

    // 3. Capture the end ticks
    clock_t end_time = clock();

    // 4. Calculate the difference
    double cpu_time_used = ((double) (end_time - start_time)) / CLOCKS_PER_SEC;

    printf("Result: %f\n", total);
    printf("CPU time consumed: %f seconds\n", cpu_time_used);

    return 0;
}

Why use this?

Imagine you are writing a game or a data-processing tool. You might have two different ways to solve a problem (Algorithm A and Algorithm B). By using clock(), you can objectively prove which one is more efficient by seeing which one uses fewer processor cycles. It is the gold standard for "profiling" or performance-tuning your C code.

Key takeaway

Use clock() to measure actual processing effort, and always divide the result by CLOCKS_PER_SEC to convert those abstract ticks into human-readable seconds.