Skip to main content

On This Page

Linux Timekeeping Internals: How RTC, TSC, and Kernel Clocks Align

2 min read
Share

These articles are AI-generated summaries. Please check the original sources for full details.

A Practical Guide to Time for Developers: Part 2 — How one computer keeps time (Linux)

The Linux kernel manages time using a multi-layered ecosystem involving hardware like the Real-Time Clock (RTC) and high-speed CPU counters. While the RTC provides a battery-backed starting point for the wall clock, the kernel translates raw hardware ticks into nanosecond-precision timelines using calibration parameters.

Why This Matters

Developers often treat time as a single point, but in technical reality, a system operates on distinct timelines—Real Time and Boot Time—that serve different purposes. Using the wrong clock, such as calculating durations with CLOCK_REALTIME instead of CLOCK_MONOTONIC, leads to critical failures when NTP adjustments or DST transitions cause the timeline to jump or move backwards.

Key Insights

  • CLOCK_REALTIME is calculated as CLOCK_MONOTONIC plus a wall_clock_offset, allowing the wall clock to be adjusted by NTP without breaking monotonic durations.
  • Modern x86 systems use the Time Stamp Counter (TSC) as a primary clocksource, which Linux calibrates to convert raw cycles into nanoseconds.
  • CLOCK_BOOTTIME differs from CLOCK_MONOTONIC by including suspend_ns, ensuring that time-since-boot tracking remains accurate even across system sleep states.
  • Time zone conversion is a user-space formatting task using tzdata rulesets rather than fixed offsets to handle historical changes and DST transitions.
  • The kernel’s timekeeping brain maintains variables like mult and shift to perform high-frequency delta-tick to nanosecond conversions on demand.

Practical Applications

  • Use Case: Distributed systems use CLOCK_MONOTONIC for measuring RPC latency and timeouts to ensure stability during system clock skews. Pitfall: Calculating durations using realtime end-start, which can result in negative values if the clock is synchronized backwards via NTP.
  • Use Case: Payroll and scheduling systems store civil time rules (e.g., Europe/Vienna) alongside UTC instants to correctly handle DST transitions. Pitfall: Storing only a local naive timestamp without a zone ID, leading to ambiguous or missing hours during fall and spring transitions.
  • Use Case: Power-sensitive applications use CLOCK_BOOTTIME to track total elapsed time since the last restart including sleep periods. Pitfall: Relying on CLOCK_MONOTONIC for long-term scheduling on mobile devices, as it often pauses during suspend.

References:

Continue reading

Next article

Automated Vulnerability Scanning for Homelab Containers with Trivy + AI

Related Content