dpdkqls6399 2016-09-08 08:17
浏览 104
已采纳

如何在Golang中每秒执行多次命令?

I want to print N lines per second.

for i := 0; i < N; i++ {
  fmt.Println(getLogs())
  time.Sleep(1000000000/N * time.Nanosecond)
}

But it seems fmt.Println() and getLogs() will also consume time. So actually it will cost me more than 1s to print N lines.

Say getLogs() and fmt.Println() will both cost 1 ms. And I want to print 1 million lines per second. Therefore, to print 1 line will cost 1 ms to getLogs(), 1 ms to print, and 1 ms to sleep... It will cost me 3s to print N lines.

Any better solutions to achieve this more accurately?

  • 写回答

2条回答 默认 最新

  • donglei2288 2016-09-08 08:40
    关注

    You may use time.NewTicker (try The Go Playground):

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        const N = 4
        ticker := time.NewTicker(1000000000 / N * time.Nanosecond)
        for i := 0; i < N; i++ {
            fmt.Println(getLogs(i))
            <-ticker.C
        }
        ticker.Stop()
    }
    
    func getLogs(i int) int {
        time.Sleep(1 * time.Millisecond)
        return i
    }
    

    output:

    0
    1
    2
    3
    

    See func NewTicker(d Duration) *Ticker Docs:

    NewTicker returns a new Ticker containing a channel that will send the time with a period specified by the duration argument. It adjusts the intervals or drops ticks to make up for slow receivers. The duration d must be greater than zero; if not, NewTicker will panic. Stop the ticker to release associated resources.


    Also see: Running code at noon in Golang

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块
  • ¥15 nhanes加权logistic回归,svyglm函数