Explain monotonic time
Explain monotonic time
The wall clock tells calendar time and can be adjusted. A monotonic clock measures elapsed time without ordinary wall-clock corrections. time.Now carries a monotonic reading when supported; when both Time operands carry it, subtraction and comparison use it. Date, Parse and Unix construct wall-only values. This lets elapsed-time calculations and calendar display share the same Time type.
package main
import ( "fmt" "time")
func main() { start := time.Now() later := start.Add(5 * time.Second) fmt.Println(later.Sub(start)) fmt.Println(later.After(start))}Add preserves the monotonic relationship of the starting value. The example constructs a relative deadline and does not wait for five seconds; output is fixed. For real elapsed work record start := time.Now(), do the work, and then use time.Since(start). Do not assert an exact elapsed duration for real work; scheduling and suspension vary, and some systems stop their monotonic clock during sleep.
Expected output:
5strueSerialized times lose the monotonic reading
package main
import ( "fmt" "time")
func check(e error) { if e != nil { panic(e) }}
func main() { t := time.Date(2026, time.January, 15, 9, 0, 0, 0, time.UTC) u, e := time.Parse(time.RFC3339, t.Format(time.RFC3339)) check(e) v := u.In(time.FixedZone("Demo", 3600)) fmt.Println(t.Equal(v)) fmt.Println(t == v) fmt.Println(t.Sub(v))}This fixed wall-only fixture shows why Equal is usually preferable to ==: == also compares internal location and monotonic state. Serialization omits monotonic readings; they are process-local. Round(0), UTC, In, Local, AddDate, Round and Truncate strip the reading. If either operand lacks it, comparisons and Sub use wall time. Normalize location and monotonic state when using Time as a map key, for example t.UTC().Round(0).
Expected output:
truefalse0sTry it locally
Construct a deadline 250 milliseconds after time.Now without sleeping. Print the difference from the original value.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Time and scheduling 06: Explain monotonic time
Check the lesson objective before moving on.
When both Time values contain monotonic readings, which clock does Sub use?
What happens to monotonic readings during JSON marshaling?