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

如何在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?

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

You can use time.Ticker something like

for range time.Tick(time.Duration(1000000000/N) * time.Nanosecond){
    fmt.Println(getLogs())
    if cond {
        break
    }
}