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

Python017

golang 获取时间精确能到纳秒吗,第1张

这样。不过只是个精确到纳秒的计时器,不是精确到纳秒的当前时间。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都是可以的。

在Go语言中,时间包提供了确定和查看时间的函数。 Go语言中的Time.Add()函数用于添加规定的时间和持续时间。此外,此函数在时间包下定义。在这里,您需要导入“time”包才能使用这些函数。

用法:

在此,“t”是规定的时间,“d”是要添加到规定时间的持续时间。

返回值: 它返回将指定的t和d相加的结果。

例:

输出:

此处,返回的输出采用上述UTC格式。