永发信息网

golang 获取时间精确能到纳秒吗

答案:1  悬赏:60  手机版
解决时间 2021-11-17 12:58
  • 提问者网友:泪痣哥哥
  • 2021-11-17 04:25
golang 获取时间精确能到纳秒吗
最佳答案
  • 五星知识达人网友:舍身薄凉客
  • 2021-11-17 04:33
这样。不过只是个精确到纳秒的计时器,不是精确到纳秒的当前时间。windows好像只能拿到ms精度的当前时间吧,不是很清楚。
package main

import (
"syscall"
"time"
"unsafe"
)

func NewStopWatch() func() time.Duration {
var QPCTimer func() func() time.Duration
QPCTimer = func() func() time.Duration {
lib, _ := syscall.LoadLibrary("kernel32.dll")
qpc, _ := syscall.GetProcAddress(lib, "QueryPerformanceCounter")
qpf, _ := syscall.GetProcAddress(lib, "QueryPerformanceFrequency")
if qpc == 0 || qpf == 0 {
return nil
}

var freq, start uint64
syscall.Syscall(qpf, 1, uintptr(unsafe.Pointer(&freq)), 0, 0)
syscall.Syscall(qpc, 1, uintptr(unsafe.Pointer(&start)), 0, 0)
if freq <= 0 {
return nil
}

freqns := float64(freq) / 1e9
return func() time.Duration {
var now uint64
syscall.Syscall(qpc, 1, uintptr(unsafe.Pointer(&now)), 0, 0)
return time.Duration(float64(now-start) / freqns)
}
}
var StopWatch func() time.Duration
if StopWatch = QPCTimer(); StopWatch == nil {
// Fallback implementation
start := time.Now()
StopWatch = func() time.Duration { return time.Since(start) }
}
return StopWatch
}

func main() {
// Call a new stop watch to create one from this moment on.
watch := NewStopWatch()
// Do some stuff that takes time.
time.Sleep(1)
// Call the stop watch itself and it will return a time.Duration
dur := watch()
}

这和语言没关系,操作系统要提供这样的原语。linux和windows都是可以的。
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯