github.com/loov/hrtime@v1.0.3/now_windows.go (about) 1 package hrtime 2 3 import ( 4 "syscall" 5 "time" 6 "unsafe" 7 ) 8 9 // precision timing 10 var ( 11 modkernel32 = syscall.NewLazyDLL("kernel32.dll") 12 procFreq = modkernel32.NewProc("QueryPerformanceFrequency") 13 procCounter = modkernel32.NewProc("QueryPerformanceCounter") 14 15 qpcFrequency = getFrequency() 16 qpcBase = getCount() 17 ) 18 19 // getFrequency returns frequency in ticks per second. 20 func getFrequency() int64 { 21 var freq int64 22 r1, _, _ := syscall.Syscall(procFreq.Addr(), 1, uintptr(unsafe.Pointer(&freq)), 0, 0) 23 if r1 == 0 { 24 panic("call failed") 25 } 26 return freq 27 } 28 29 // getCount returns counter ticks. 30 func getCount() int64 { 31 var qpc int64 32 syscall.Syscall(procCounter.Addr(), 1, uintptr(unsafe.Pointer(&qpc)), 0, 0) 33 return qpc 34 } 35 36 // Now returns current time.Duration with best possible precision. 37 // 38 // Now returns time offset from a specific time. 39 // The values aren't comparable between computer restarts or between computers. 40 func Now() time.Duration { 41 return time.Duration(getCount()-qpcBase) * time.Second / (time.Duration(qpcFrequency) * time.Nanosecond) 42 } 43 44 // NowPrecision returns maximum possible precision for Now in nanoseconds. 45 func NowPrecision() float64 { 46 return float64(time.Second) / (float64(qpcFrequency) * float64(time.Nanosecond)) 47 }