简体   繁体   中英

High resolution timers (millisecond precision) in Go on Windows

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?

从Go 1.7开始,计时器现在具有更高的分辨率,并且不应出现此问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM