Created
January 11, 2017 09:45
-
-
Save wspl/9d28ef06112f0c9d0f31ff55cd5a2066 to your computer and use it in GitHub Desktop.
(Go) High Resolution Timer / Sleeper for Windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"syscall" | |
"unsafe" | |
"time" | |
) | |
var ( | |
kernel32Dll = syscall.NewLazyDLL("kernel32.dll") | |
winapiQueryPerformanceCounter = kernel32Dll.NewProc("QueryPerformanceCounter") | |
winapiQueryPerformanceFrequency = kernel32Dll.NewProc("QueryPerformanceFrequency") | |
performanceFrequency float64 | |
) | |
// GetNanoTime get time in nanoseconds from native timer | |
func GetNanoTime() (int64, error) { | |
var out int64 | |
if performanceFrequency == 0 { | |
ret, _, err := winapiQueryPerformanceFrequency.Call(uintptr(unsafe.Pointer(&out))) | |
if ret == 0 { | |
return 0, err | |
} | |
performanceFrequency = float64(out) | |
} | |
ret, _, err := winapiQueryPerformanceCounter.Call(uintptr(unsafe.Pointer(&out))) | |
if ret == 0 { | |
return 0, err | |
} | |
return int64((float64(out) / performanceFrequency) * 1e9), nil | |
} | |
// Sleep via while lock and GetNanoTime | |
func SuperSleep(d time.Duration) { | |
startTime, _ := GetNanoTime() | |
getDuration := func() int64 { | |
currentTime, _ := GetNanoTime() | |
return currentTime - startTime | |
} | |
for { | |
if getDuration() > int64(d.Nanoseconds()) { | |
break | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment