go语言学习计时器 go语言定时器( 二 )


Go by
Example上有大量的实例,能帮助开拓视野;
GopherAcademy有很多有关Go最佳实践的文章 。
golang 获取时间精确能到纳秒吗这样 。不过只是个精确到纳秒的计时器,不是精确到纳秒的当前时间 。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语言定时器】go语言学习计时器的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于go语言定时器、go语言学习计时器的信息别忘了在本站进行查找喔 。

推荐阅读