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 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?