drd99007 2016-06-08 15:28
浏览 348

Windows上的高分辨率计时器(毫秒级精度)

I'm trying to use Go's time.Timers 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?

  • 写回答

1条回答 默认 最新

  • dongxifu5009 2017-06-17 21:31
    关注

    Since Go 1.7, timers now have a higher resolution and this problem should not occur.

    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?