Skip to content

Instantly share code, notes, and snippets.

@khaosdoctor
Last active June 26, 2022 22:40
Show Gist options
  • Save khaosdoctor/21f60b652f431cda597a3d26de236956 to your computer and use it in GitHub Desktop.
Save khaosdoctor/21f60b652f431cda597a3d26de236956 to your computer and use it in GitHub Desktop.
Code to experiment with clock drift in MacOS
// Inspired by https://blog.insiderattack.net/how-not-to-measure-time-in-programming-11089d546180
import { execSync } from 'node:child_process'
import { setTimeout } from 'node:timers/promises'
import { performance } from 'node:perf_hooks'
function adiantarTempo () {
const toTwoDigits = (num) => num.toString().padStart(2, "0")
const now = new Date()
const month = toTwoDigits(now.getMonth() + 1)
const date = toTwoDigits(now.getDate())
const hours = toTwoDigits(now.getHours())
const fakeMinutes = toTwoDigits(now.getMinutes() + 1)
const year = now.getFullYear().toString().substring(2, 4)
// set fake time
execSync(`date -u ${month}${date}${hours}${fakeMinutes}${year}`)
}
function correcaoNTP () {
const output = execSync(`sntp -sS time.apple.com`)
console.log(`Tempo corrigido: ${output}`)
}
const esperar2Segundos = () => setTimeout(2000)
// ------- Experimento 1: Relógios normais
{
adiantarTempo()
const timeNow = Date.now()
setImmediate(() => correcaoNTP())
await esperar2Segundos()
const endTime = Date.now()
const duration = endTime - timeNow
console.log(`Duração\t: ${duration}ms`)
}
// ------- Experimento 2: Relógios monotonicos
{
adiantarTempo()
const timeNow = performance.now()
setImmediate(() => correcaoNTP())
await esperar2Segundos()
const endTime = performance.now()
const duration = endTime - timeNow
console.log(`Duração\t: ${duration}ms`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment