Skip to content
Visual explainer 3h 30m to learn 5 steps

Clocks, sleeping & timers

Measure elapsed time with the right clock and drive periodic work with timerfd.

By Invicly Tech, , in Linux System Programming. About 13 minutes to read.

Topic 37 of 42

In short

Linux has several clocks: CLOCK_REALTIME follows wall-clock time and can jump, while CLOCK_MONOTONIC only moves forward and is right for measuring durations. clock_gettime reads them cheaply through the vDSO. timerfd turns timers into descriptors, so periodic work fits neatly into a poll or epoll loop.

Explained simply

A computer has more than one clock. One shows the time of day, like the clock on the wall. It can be changed: by an admin, or by NTP when it corrects the time. Another clock just counts forward from boot and is never changed. It cannot tell you the date, but it is perfect for measuring how long something took.

Mixing them up causes real bugs. If you measure a download with the wall clock and NTP moves the clock back 2 seconds in the middle, the download seems to take negative time. Timeouts can fire far too early or never.

For waiting, Linux gives you sleeps (stop this thread for a while) and timers (tell me when time is up). A timerfd is a timer that looks like a file descriptor: it becomes readable when the timer fires, so it fits into the same poll or epoll loop as your sockets.

The rule of thumb is short: timestamps for humans use CLOCK_REALTIME, everything about durations and timeouts uses CLOCK_MONOTONIC.

Press Play on a diagram to walk through it one step at a time.

CompareWhich clock to use
CLOCK_REALTIME
  • Wall-clock time since 1970
  • Jumps when NTP or an admin sets the time
  • Use for timestamps and logs
  • Same source as time() and gettimeofday()
CLOCK_MONOTONIC
  • Steadily increasing since boot
  • Never jumps backwards
  • Use for timeouts and durations
  • Does not count time in suspend
CLOCK_BOOTTIME
  • Like MONOTONIC
  • Includes time spent suspended
  • Use when sleep time must count
  • Linux specific
SequenceTwo clocks when NTP steps the time back
Program
CLOCK_REALTIME
CLOCK_MONOTONIC
  1. 1start: 12:00:10.0
    Program to CLOCK_REALTIME: start: 12:00:10.0
  2. 2start: 5000.0 s
    Program to CLOCK_MONOTONIC: start: 5000.0 s
  3. 3NTP steps the clock back 3 s
    CLOCK_REALTIME to CLOCK_REALTIME: NTP steps the clock back 3 s
  4. 4end: 12:00:08.0, elapsed -2 s (wrong)
    Program to CLOCK_REALTIME: end: 12:00:08.0, elapsed -2 s (wrong)
  5. 5end: 5001.0 s, elapsed 1 s (right)
    Program to CLOCK_MONOTONIC: end: 5001.0 s, elapsed 1 s (right)

In depth

The full family of clocks

Besides REALTIME, MONOTONIC and BOOTTIME, Linux has a few more clocks worth knowing. CLOCK_MONOTONIC is not completely untouched: NTP may speed it up or slow it down slightly (slewing) to keep it accurate, but it never jumps. CLOCK_MONOTONIC_RAW has no NTP adjustment at all, which is useful when comparing against hardware.

The _COARSE variants (CLOCK_REALTIME_COARSE, CLOCK_MONOTONIC_COARSE) are even cheaper to read but only update once per kernel tick, so their resolution is typically 1 to 4 milliseconds. CLOCK_PROCESS_CPUTIME_ID and CLOCK_THREAD_CPUTIME_ID do not measure wall time at all but CPU time used by the process or thread, which is what you want when profiling a function that also waits for I/O.

clock_getres(clock, &res) tells you the resolution of each clock. For the normal clocks on modern hardware it reports 1 nanosecond, which is the unit, not a promise of accuracy.

MapLinux clocks by purpose
clock_gettime(clock, &ts)
  • Time of day
    • CLOCK_REALTIME
    • CLOCK_REALTIME_COARSE (cheaper, ms resolution)
  • Durations and timeouts
    • CLOCK_MONOTONIC
    • CLOCK_MONOTONIC_RAW (no NTP adjustment)
    • CLOCK_BOOTTIME (counts suspend)
  • CPU time used
    • CLOCK_PROCESS_CPUTIME_ID
    • CLOCK_THREAD_CPUTIME_ID

Measuring durations correctly

Read CLOCK_MONOTONIC before and after the work and subtract. A struct timespec has tv_sec and tv_nsec, so subtract both and borrow one second when the nanoseconds go negative, or convert each reading to a single 64-bit nanosecond count first, which is simpler.

clock_gettime is fast because of the vDSO: for these clocks the kernel maps a small page of time data into every process, and glibc reads it without a system call, in roughly 20 to 50 nanoseconds. You can call it often without worry.

For tiny pieces of code, a single measurement lies. CPU caches are cold the first time, the CPU may be changing frequency, and the scheduler may interrupt you. Repeat the work many times, discard the first runs, and report the median or minimum. Avoid time() (one-second resolution) and gettimeofday (wall clock, microseconds) for this job.

  • int64_t ns = ts.tv_sec * 1000000000LL + ts.tv_nsec;
  • Repeat and take the median for micro-benchmarks
  • perf stat ./prog for whole-program timing and counters

Sleeping precisely

nanosleep(&req, &rem) sleeps for a relative duration. If a signal handler interrupts it, it returns -1 with EINTR and writes the time left into rem, so you can sleep again for the rest. The kernel never wakes you early, but it may wake you a little late: there is scheduling delay, and normal threads have a timer slack of 50 microseconds by default, which lets the kernel group nearby wakeups to save power.

The bigger problem is drift in periodic loops. Doing work and then sleeping 100 ms each time means each period is 100 ms plus the work time plus the wakeup delay, so the loop falls behind. Instead, keep an absolute deadline, add the period to it each time, and sleep until that moment with clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, NULL). Delays no longer add up. Note that clock_nanosleep returns the error number directly (like pthreads) instead of setting errno.

ComparePeriodic loop: relative vs absolute sleep
Relative: work, then sleep 100 ms
  • Each period = 100 ms + work + delay
  • Error grows every cycle
  • After an hour, many ticks are lost
  • Fine for one-off delays
Absolute: next += 100 ms
  • Sleeps until a fixed deadline
  • Work time is absorbed
  • No drift over time
  • clock_nanosleep with TIMER_ABSTIME

timerfd in detail

timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC) returns a descriptor. timerfd_settime(fd, flags, &new, &old) arms it with a struct itimerspec: it_value is the first expiry, it_interval the period after that. An it_interval of zero makes a one-shot timer, and an it_value of zero disarms it. With TFD_TIMER_ABSTIME in flags, it_value is an absolute time on the timer's clock instead of a delay.

When the timer expires, the descriptor becomes readable. read must use an 8-byte buffer and returns a uint64_t count of expirations since the last read. If your loop was busy and missed some ticks, the count is larger than 1, so you know exactly how many periods passed. Reading resets the count. If nothing expired, a blocking read waits; a non-blocking one returns EAGAIN.

Older alternatives are alarm and setitimer, which deliver SIGALRM, and POSIX timers from timer_create. Signals are harder to handle safely, which is why timerfd is the usual choice in event loops.

  • it_interval = 0: one-shot; it_value = 0: disarm
  • read gives a uint64_t expiration count
  • Watch it in epoll like any socket

Timeouts in poll and epoll

poll and epoll_wait take a timeout in milliseconds: -1 waits forever, 0 returns at once. The kernel rounds it up to its clock granularity, so the wait can be a little longer, never shorter. For finer control, ppoll takes a struct timespec, and epoll_pwait2 (Linux 5.11 and later) does the same for epoll.

The classic bug is reusing the same timeout after an early return. If poll returns because of a signal (EINTR) or an event you ignore, and you call it again with the full 5000 ms, the total wait can be much longer than 5 seconds. The cure is a deadline: compute deadline = now + timeout once, from CLOCK_MONOTONIC, and before every call pass remaining = deadline - now, stopping when it reaches zero. Event loops do the same thing with their timer list: the next deadline decides the epoll_wait timeout.

FlowWaiting with a deadline
  1. Step 1
    deadline = now + 5 s

    Read CLOCK_MONOTONIC once

  2. Step 2
    remaining = deadline - now

    Recompute before every wait

  3. Step 3
    poll(fds, n, remaining)

    Returns on event, timeout or EINTR

  4. Step 4
    Not done? loop

    Stop when remaining reaches 0

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Compare CLOCK_REALTIME and CLOCK_MONOTONIC~40m
  2. 2
    Measure durations with clock_gettime~40m
  3. 3
    Sleep precisely with nanosleep~40m
  4. 4
    Create periodic timers with timerfd~40m
  5. 5
    Add timeouts to poll and epoll~40m

Key points

  • Never measure elapsed time with wall-clock time, because it can jump.
  • nanosleep can return early with EINTR; clock_nanosleep with TIMER_ABSTIME avoids drift.
  • timerfd_create and timerfd_settime give a descriptor that becomes readable on schedule.
  • Reading a timerfd returns how many expirations happened since the last read.

Key terms

Tap a card to flip it. 0/5 known

Examples

c
#include <stdint.h>
#include <stdio.h>
#include <sys/timerfd.h>
#include <time.h>
#include <unistd.h>
int main(void) {
  int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
  struct itimerspec its = { .it_value = { 1, 0 }, .it_interval = { 0, 500000000 } };
  timerfd_settime(tfd, 0, &its, NULL);
  for (int i = 0; i < 5; i++) {
    uint64_t exp; read(tfd, &exp, sizeof exp);
    struct timespec now; clock_gettime(CLOCK_MONOTONIC, &now);
    printf("tick %d at %ld.%03ld s\n", i, (long)now.tv_sec, now.tv_nsec / 1000000);
  }
}

First tick after 1 s, then every 500 ms.

Time a function in milliseconds

We want to know how long a piece of work takes. Step 1: write a helper that reads CLOCK_MONOTONIC and returns nanoseconds as one 64-bit integer, which avoids the borrow logic of timespec subtraction. Step 2: read it before and after the work. Step 3: also read the process CPU-time clock, so we can see whether the work was busy computing or mostly waiting. Here the work sleeps, so wall time is about 200 ms while CPU time is near 0.

c
#include <stdint.h>
#include <stdio.h>
#include <time.h>
static int64_t ns(clockid_t c) {
  struct timespec ts;
  if (clock_gettime(c, &ts) < 0) { perror("clock_gettime"); return 0; }
  return (int64_t)ts.tv_sec * 1000000000 + ts.tv_nsec;
}
int main(void) {
  int64_t w0 = ns(CLOCK_MONOTONIC), c0 = ns(CLOCK_PROCESS_CPUTIME_ID);
  struct timespec d = { 0, 200000000 }; nanosleep(&d, NULL);   /* the "work" */
  printf("wall %.1f ms, cpu %.3f ms\n",
         (ns(CLOCK_MONOTONIC) - w0) / 1e6, (ns(CLOCK_PROCESS_CPUTIME_ID) - c0) / 1e6);
  return 0;
}

A periodic loop that does not drift

A sensor must be read every 100 ms for hours. Step 1: take the start time from CLOCK_MONOTONIC. Step 2: each loop, add 100 ms to the deadline and normalise the nanoseconds. Step 3: sleep until that absolute time with TIMER_ABSTIME. Step 4: clock_nanosleep returns the error code itself; on EINTR, simply sleep again until the same deadline. However long the work takes (as long as it is under 100 ms), tick 36000 happens one hour after the start.

c
#include <errno.h>
#include <stdio.h>
#include <time.h>
int main(void) {
  struct timespec next;
  clock_gettime(CLOCK_MONOTONIC, &next);
  for (long tick = 0; tick < 36000; tick++) {
    next.tv_nsec += 100000000;                              /* + 100 ms */
    if (next.tv_nsec >= 1000000000) { next.tv_sec++; next.tv_nsec -= 1000000000; }
    int rc;
    while ((rc = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, NULL)) == EINTR) {}
    if (rc) { fprintf(stderr, "clock_nanosleep: error %d\n", rc); return 1; }
    /* read_sensor(); */
  }
  return 0;
}

Quick reference

  • Durations and timeouts: CLOCK_MONOTONIC; log timestamps: CLOCK_REALTIME
  • clock_gettime goes through the vDSO: no syscall, tens of nanoseconds
  • CLOCK_PROCESS_CPUTIME_ID measures CPU time used, not wall time
  • nanosleep on EINTR: sleep again for the time left in rem
  • Periodic work: clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, NULL)
  • clock_nanosleep returns the error number; it does not set errno
  • timerfd read needs 8 bytes and returns the number of expirations
  • Keep a monotonic deadline and pass the remaining time to poll each call

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which clock should a 30-second idle timeout use?

Question 2

2A loop does 20 ms of work and then nanosleeps 100 ms. How long is each period?

Question 3

3A read from a periodic timerfd returns 3. What does that mean?

Question 4

4poll with a 5000 ms timeout keeps returning early with EINTR, and the code retries with 5000 each time. What is wrong?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Print the resolution and the current value of CLOCK_REALTIME, CLOCK_MONOTONIC, CLOCK_MONOTONIC_COARSE and CLOCK_BOOTTIME.

  2. Exercise 2medium

    Watch standard input and a 1-second timerfd in the same poll loop: echo typed lines, and print "tick N" each second, with N counting missed ticks too.

  3. Exercise 3hard

    Write int wait_readable(int fd, int timeout_ms) that returns 1 when fd is readable, 0 on timeout and -1 on error, and keeps the total wait correct across EINTR.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is CLOCK_MONOTONIC the same on every machine?
No. It usually counts from boot, so values from two machines (or two boots) cannot be compared. Use it only for differences within one running system.
Why does my 1 ms sleep take 1.1 ms?
The kernel never wakes you early but adds scheduling delay and timer slack (50 microseconds by default). Real-time scheduling or prctl(PR_SET_TIMERSLACK) can tighten it.
Does CLOCK_MONOTONIC stop during suspend?
Yes, on Linux it does not count time spent suspended. Use CLOCK_BOOTTIME if the suspended time must be included.
Should I use alarm or SIGALRM for timeouts?
Avoid them in new code. Signals interrupt any call at any moment and there is only one alarm per process. timerfd or a poll timeout is easier to get right.

Go deeper

ShareXLinkedInWhatsApp