1

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?

Rick-777
  • 9,714
  • 5
  • 34
  • 50
Haoyuan Ge
  • 3,379
  • 3
  • 24
  • 40
  • [time.NewTicker()](https://godoc.org/time#NewTicker) perhaps? i dont really get your objective. as written, as N increases, the sleep time DECREASES – Plato Sep 08 '16 at 08:36
  • @Plato ticker works if a ticker counts time in parallel to fmt.Println and getLogs, – Haoyuan Ge Sep 08 '16 at 09:37

2 Answers2

5

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

Community
  • 1
  • 1
0

You can use time.Ticker something like

for range time.Tick(time.Duration(1000000000/N) * time.Nanosecond){
    fmt.Println(getLogs())
    if cond {
        break
    }
}
Uvelichitel
  • 8,220
  • 1
  • 19
  • 36