# Time 11, Exercise 2: clock drift, leap seconds and asking a time server # Part 1: how often must a computer clock be corrected? SECONDS_PER_DAY = 86400 for ppm in (10, 50): per_day = ppm * 1e-6 * SECONDS_PER_DAY print(ppm, "ppm drifts", round(per_day, 2), "s a day") # time until the error reaches 10 milliseconds (0.01 s) seconds_to_10ms = 0.010 / (ppm * 1e-6) print(" reaches 10 ms after", round(seconds_to_10ms / 60, 1), "minutes") # Part 2: leap seconds. Since 1972 UTC has had 27 of them (the last on 31 December 2016). # On 1 January 1972, TAI was 10 s ahead of UTC. leaps = 27 print("TAI minus UTC today:", 10 + leaps, "s") print("GPS minus UTC today:", 10 + leaps - 19, "s") # GPS time started 19 s behind TAI print("seconds in a day with a leap second:", SECONDS_PER_DAY + 1) print("average leap seconds per year, 1972-2016:", round(leaps / (2016 - 1972 + 1), 2)) # Part 3: the four-timestamp calculation used by NTP. # t0: client sends request (client clock) t1: server receives (server clock) # t2: server replies (server clock) t3: client receives reply (client clock) t0, t1, t2, t3 = 100.000, 100.550, 100.551, 100.101 delay = (t3 - t0) - (t2 - t1) offset = ((t1 - t0) + (t2 - t3)) / 2 print("round-trip delay:", round(delay, 3), "s") print("client clock is off by:", round(offset, 3), "s (positive = client is behind)") # Output when run: # 10 ppm drifts 0.86 s a day # reaches 10 ms after 16.7 minutes # 50 ppm drifts 4.32 s a day # reaches 10 ms after 3.3 minutes # TAI minus UTC today: 37 s # GPS minus UTC today: 18 s # seconds in a day with a leap second: 86401 # average leap seconds per year, 1972-2016: 0.6 # round-trip delay: 0.1 s # client clock is off by: 0.5 s (positive = client is behind) # Reading the output: a cheap 50 ppm clock can be 10 ms wrong within about three minutes, which # is why computers ask a time server again and again. In the NTP sums, the round trip took 0.1 s # once the server's 0.001 s of thinking time is taken off. Averaging the two one-way differences # cancels the travel time (if it was the same each way), leaving a clock error of half a second.