This is timers/clock_times.c, an example to accompany the book, The Linux Programming Interface.

This file is not printed in the book; it is a supplementary file for Chapter 23.

The source code file is copyright 2022, Michael Kerrisk, and is licensed under the GNU General Public License, version 3.

In the listing below, the names of Linux system calls and C library functions are hyperlinked to manual pages from the Linux man-pages project, and the names of functions implemented in the book are hyperlinked to the implementations of those functions.


Download timers/clock_times.c

  Cover of The Linux Programming Interface

Function list (Bold in this list means a function is not static)

/* clock_times.c

   Display the values of the CLOCK_REALTIME, CLOCK_MONOTONIC, and
   CLOCK_BOOTTIME clocks. A useful small program for time namespaces.
#define _XOPEN_SOURCE 600
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>

#define SECS_IN_DAY (24 * 60 * 60)
static void
displayClock(clockid_t clock, char *name, bool showRes)
    struct timespec ts;

    if (clock_gettime(clock, &ts) == -1) {

    printf("%-15s: %10ld.%03ld (", name,
            (long) ts.tv_sec, ts.tv_nsec / 1000000);

    long days = ts.tv_sec / SECS_IN_DAY;
    if (days > 0)
        printf("%ld days + ", days);

    printf("%2ldh %2ldm %2lds", (ts.tv_sec % SECS_IN_DAY) / 3600,
            (ts.tv_sec % 3600) / 60, ts.tv_sec % 60);

    if (clock_getres(clock, &ts) == -1) {

    if (showRes)
        printf("     resolution: %10ld.%09ld\n",
                (long) ts.tv_sec, ts.tv_nsec);
main(int argc, char *argv[])
    bool showRes = argc > 1;

    displayClock(CLOCK_REALTIME, "CLOCK_REALTIME", showRes);
#ifdef CLOCK_TAI
    displayClock(CLOCK_TAI, "CLOCK_TAI", showRes);
    displayClock(CLOCK_MONOTONIC, "CLOCK_MONOTONIC", showRes);
    displayClock(CLOCK_BOOTTIME, "CLOCK_BOOTTIME", showRes);


Download timers/clock_times.c

Note that, in most cases, the programs rendered in these web pages are not free standing: you'll typically also need a few other source files (mostly in the lib/ subdirectory) as well. Generally, it's easier to just download the entire source tarball and build the programs with make(1). By hovering your mouse over the various hyperlinked include files and function calls above, you can see which other source files this file depends on.

Valid XHTML 1.1