Skip to content

Instantly share code, notes, and snippets.

@christos68k
Last active March 30, 2024 04:03
Show Gist options
  • Save christos68k/cd29fd45e08b6fdc6585a15ddde04321 to your computer and use it in GitHub Desktop.
Save christos68k/cd29fd45e08b6fdc6585a15ddde04321 to your computer and use it in GitHub Desktop.
monotonic clock sync tests
package main
import (
"fmt"
"sort"
"time"
_ "unsafe"
"golang.org/x/sys/unix"
)
const (
sampleSize = 5
diffNs = 60 * 1e9
)
var samples = make([]struct {
ts1 unix.Timespec
ktime int64
ts2 unix.Timespec
}, sampleSize)
//go:noescape
//go:linkname getKTime runtime.nanotime
func getKTime() int64
func getSample() {
for i := range samples {
unix.ClockGettime(unix.CLOCK_BOOTTIME, &samples[i].ts1)
samples[i].ktime = getKTime()
unix.ClockGettime(unix.CLOCK_BOOTTIME, &samples[i].ts2)
}
sort.Slice(samples, func(i, j int) bool {
t1 := samples[i].ts2.Nano() - samples[i].ts1.Nano()
t2 := samples[j].ts2.Nano() - samples[j].ts1.Nano()
return t1 < t2
})
resync := ""
diff := samples[0].ktime - samples[0].ts1.Nano()
if diff < 0 {
diff = -diff
}
if diff > diffNs {
resync = fmt.Sprintf(" RESYNC: %v", diff/1e9)
}
fmt.Printf("t1: %v t2: %v kt: %v t2-t1: %v d: %v%v\n",
samples[0].ts1.Nano(),
samples[0].ts2.Nano(),
samples[0].ktime,
samples[0].ts2.Nano()-samples[0].ts1.Nano(),
diff,
resync,
)
}
func main() {
for {
getSample()
time.Sleep(3 * time.Second)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment