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 newTicker
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments