How the kernel keeps time: clock sources (TSC/HPET) vs clock event devices, HZ/jiffies and the tick, tickless (NOHZ_IDLE/NOHZ_FULL), timer wheel vs hrtimers, REALTIME vs MONOTONIC clocks, and fast clock_gettime via the vDSO.
How the kernel keeps time and drives everything on a schedule — the tick, timers, clock sources, and the clocks your code reads. Original, interview-focused notes; pairs with the network side in PTP & Time Sync.
Separate two ideas: timekeeping (what time is it? — driven by a hardware clock source) and timers/the tick (do something after N ns — driven by a clock event device). And two clocks your code reads: REALTIME (wall-clock, can jump) vs MONOTONIC (never goes backward — use it for intervals).
/sys/devices/system/clocksource/…/current_clocksource.HZ times per second
(typically 100/250/1000). Each tick bumps jiffies, the coarse "ticks since boot"
counter, and does per-tick work (accounting, scheduler check, timers).jiffies is coarse (1–10 ms); don't use it for
precise timing.isolcpus.| Kind | Granularity | Use |
|---|---|---|
Timer wheel (timer_list) | jiffies (coarse) | Cheap timeouts where ~ms slack is fine (most kernel timeouts). |
| hrtimers | ns (high-res) | Precise wakeups — nanosleep, scheduler, POSIX timers. |
hrtimers are stored in a time-ordered tree and fired by the clock-event device, so accuracy doesn't depend on HZ.
| Clock | Behavior |
|---|---|
CLOCK_REALTIME | Wall-clock (UTC). Can jump (NTP/admin/PTP steps) — don't measure intervals with it. |
CLOCK_MONOTONIC | Since boot, never decreases (NTP only slews the rate). The right clock for elapsed time. |
CLOCK_MONOTONIC_RAW | Monotonic, not even NTP-adjusted. |
CLOCK_BOOTTIME | Monotonic + counts suspend time. |
CLOCK_PROCESS/THREAD_CPUTIME | CPU time consumed, for profiling. |
Fast reads: clock_gettime() on REALTIME/MONOTONIC is served by the
vDSO — it reads the TSC in user space with no syscall, so it's cheap enough to call
in hot loops. (See System Calls.)
clock_gettime cheap? (vDSO reads the TSC without a syscall)