英文:
How do I execute commands many many times per second in Golang?
问题
我想每秒打印N
行。
for i := 0; i < N; i++ {
fmt.Println(getLogs())
time.Sleep(1000000000/N * time.Nanosecond)
}
但是似乎fmt.Println()
和getLogs()
也会消耗时间。所以实际上打印N
行会比1秒更长。
假设getLogs()
和fmt.Println()
各需要1毫秒的时间。我想每秒打印100万行。因此,打印1行需要1毫秒的时间来执行getLogs()
,1毫秒的时间来打印,还有1毫秒的时间来休眠... 打印N行将花费我3秒的时间。
有没有更准确地实现这个目标的更好方法?
英文:
I want to print N
lines per second.
<!-- language: lang-golang -->
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?
答案1
得分: 5
你可以使用time.NewTicker
函数来实现(可以尝试在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
}
输出结果为:
0
1
2
3
请参阅func NewTicker(d Duration) *Ticker
的文档:
NewTicker
函数返回一个新的Ticker
,其中包含一个通道,该通道将按照指定的时间间隔发送时间。它会调整间隔或丢弃滞后的接收者的时间。持续时间d
必须大于零;否则,NewTicker
将会引发错误。停止Ticker
以释放相关资源。
还可以参考:https://stackoverflow.com/questions/38386762/running-code-at-noon-golang
英文:
You may use time.NewTicker
(try The Go Playground):
<!-- language: lang-golang -->
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: https://stackoverflow.com/questions/38386762/running-code-at-noon-golang
答案2
得分: 0
你可以使用time.Ticker
来实现,类似于以下代码:
for range time.Tick(time.Duration(1000000000/N) * time.Nanosecond){
fmt.Println(getLogs())
if cond {
break
}
}
这段代码会每隔一定时间执行一次getLogs()
函数,并在满足条件时退出循环。
英文:
You can use time.Ticker
something like
for range time.Tick(time.Duration(1000000000/N) * time.Nanosecond){
fmt.Println(getLogs())
if cond {
break
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论