liveBook · Manning

Clock

As explained in 100 Go Mistakes and How to Avoid Them

A wall clock is a clock that represents the current time of day and may jump forward or backward when synchronized.

A wall clock represents the current time of day, but synchronization such as NTP can make it jump forward or backward. Do not measure durations with it: backward jumps can produce negative durations. A monotonic clock instead moves forward continuously and is not affected by time jumps. section 10.3.2

When JSON changes a time comparison

Calling time.Now() can produce a time.Time containing both wall and monotonic time. JSON preserves the wall time but drops the monotonic value, so comparing the original and unmarshaled structs with == prints false even though they represent the same instant. Use time.Time.Equal for instant comparison, or remove the monotonic component with Truncate(0) before a structural comparison.

Choose the operation according to what the timestamp means:

  • Use the wall time to represent calendar or clock time, including values serialized through JSON. section 10.3.2
  • Use a monotonic clock for elapsed-time measurement when clock synchronization could otherwise distort the result. section 10.3.2
  • Use Equal instead of == when comparing time.Time values that may have different monotonic components. section 10.8

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Distinguishes wall and monotonic clocks, traces JSON’s loss of monotonic data, and contrasts == with Equal.
Examples
Uses a time.Time JSON round trip, printed monotonic data, Equal, and Truncate(0) to expose comparison differences.
What it assumes
Assumes familiarity with Go structs, time.Time, JSON marshaling, and basic equality comparisons.
What you can do after
Diagnose misleading time.Time comparisons and choose Equal, Truncate(0), or monotonic timing appropriately.
How it connects
Connects wall clocks to monotonic clocks, time.Time, JSON marshaling, NTP synchronization, and duration measurement.

Also explained in

Compare how 5 books explain clock →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.