typestar

Measuring elapsed time in C

clock counts processor time; use CLOCKS_PER_SEC to make it meaningful.

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

double time_work(long iterations) {
    clock_t started = clock();

    volatile long sink = 0;
    for (long i = 0; i < iterations; i++) {
        sink += i % 7;
    }

    clock_t finished = clock();
    return (double) (finished - started) / CLOCKS_PER_SEC;
}

void benchmark(void) {
    printf("%.4f seconds\n", time_work(5000000L));
}

How it works

  1. clock() returns processor time, not wall-clock time.
  2. Dividing by CLOCKS_PER_SEC gives seconds.
  3. For wall-clock, time or a POSIX clock is the right call.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
341
Tokens
90
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 54 seconds.

Type this snippet

Step 2 of 2 in Time, step 6 of 14 in Systems programming.

← Previous Next →