Close

The monotonic clock in Linux

A project log for Silly software wishlist

Motivation to do some software projects by writing them down.

lion-mclionheadlion mclionhead 04/23/2020 at 20:540 Comments

Lions finally discovered the monotonic clock, after 25 years of using calendar time functions to calculate delays & timeouts.  The calendar time jumps around when the system time changes.  The monotonic time always increases at a constant rate.  To be fair, the monotonic time functions didn't exist on Linux until 20 years ago.

Most programs lions have written to use calendar time don't want the calendar time but the monotonic time.  Lions started using a system clock of some kind, probably around 1995.  Before then, what little programming they did was on 8 bit computers with no realtime clock.  Delays involved just incrementing counters or waiting for the raster interrupt.  That's still the way it's done on microcontrollers.

Where the calendar time came from gettimeofday, the monotonic time comes from clock_gettime

clock_gettime(CLOCK_MONOTONIC, struct timespec *tp);

It returns a nanosecond field while gettimeofday has a microsecond field. 

Helas, it's not as monotonic as it seems.  A user can call clock_settime to set the monotonic clock, just like the realtime clock.  In Linux, clock_settime seems to not work for the monotonic clock.

Reviewing /usr/include/x86_64-linux-gnu/bits/time.h, there are actually many other clocks besides the monotonic & the calendar.  There's a clock which responds to frequency scaling, a clock that counts suspension times, a clock that counts just cpu usage, a clock that counts cpu usage per thread.  clock_gettime has become a replacement for much of the /proc filesystem.

The monotonic clock is supposedly part of the POSIX standard, but POSIX these days just means Linux.  If it didn't exist in Linux, it didn't exist anywhere.  It doesn't require librt on Linux.

Discussions