I'm trying to use Go's time.Timer
s to schedule tasks that need to be run in the right order with a precision in the order of half a millisecond. This works perfectly fine on OSX and on Linux, but fails every time on Windows.
The following code demonstrates the issue. It sets 5 timers, the first one to 1 ms, the second to 2 ms, ..., and the last one to 5 ms. Once a timer fires, its number is printed. On OSX and Linux, this obviously produced "12345" as output, but on Windows the numbers are more or less random (tested on Win 7 and Windows Server 2012).
package main
import (
"fmt"
"time"
)
func main() {
var timer1, timer2, timer3, timer4, timer5 *time.Timer
timer1 = time.NewTimer(1 * time.Millisecond)
timer2 = time.NewTimer(2 * time.Millisecond)
timer3 = time.NewTimer(3 * time.Millisecond)
timer4 = time.NewTimer(4 * time.Millisecond)
timer5 = time.NewTimer(5 * time.Millisecond)
// should print 12345
for {
select {
case <-timer1.C:
fmt.Print("1")
case <-timer2.C:
fmt.Print("2")
case <-timer3.C:
fmt.Print("3")
case <-timer4.C:
fmt.Print("4")
case <-timer5.C:
fmt.Print("5")
case <-time.After(200 * time.Millisecond):
return // exit the program
}
}
}
I think this behavior is due to the changes made in Go 1.6 (https://golang.org/doc/go1.6#runtime, 4th paragraph), where the Windows timer precision was reduced from 1 ms to 16 ms, although it should also have occurred with shorter intervals (of the order of 100 μs) before.
Is there any way to reset the global Windows timer precision back to 1 ms, or to access a high resolution timer that would make the example above work?
Since Go 1.7, timers now have a higher resolution and this problem should not occur.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With