【发布时间】:2021-07-02 06:10:46
【问题描述】:
无法找出我们在下面的 for 循环中的哪个位置花费了超过 10 微秒,从而丢失了大量的滴答声?
package main
import (
"context"
"fmt"
"time"
)
func main() {
RunTicker(time.Millisecond, 10 * time.Second) // Scenario 1
RunTicker(10 * time.Microsecond, 10 * time.Second) // Scenario 2
}
func RunTicker(tickerInterval, tickerDuration time.Duration) {
var counter int
ctx, can := context.WithTimeout(context.Background(), tickerDuration)
defer can()
ticker := time.NewTicker(tickerInterval)
exitfor:
for {
select {
case <-ticker.C:
counter++
case <- ctx.Done():
ticker.Stop()
break exitfor
}
}
fmt.Printf("Tick interval %v and running for %v.Expected counter: %d but got %d\n", tickerInterval, tickerDuration, tickerDuration/tickerInterval, counter)
}
输出:
Tick interval 1ms and running for 10s.Expected counter: 10000 but got 9965
Tick interval 10µs and running for 10s.Expected counter: 1000000 but got 976590
【问题讨论】:
-
我不会称它为您所缺少的“大量数字”。在您的测试中,您获得了 99% 和 97% 的预期值。
-
感谢您的回复。但我的问题是什么是停止获得 100% 的预期值?
-
那应该是
counter++延迟 -
我也这么认为。所以我只对这个陈述进行了基准测试。花费的时间不超过几纳秒。
-
根据操作系统和硬件,系统时钟可能无法提供微秒精度,甚至是单毫秒精度。 Go 的计时系统自然受限于运行环境的计时系统。
标签: performance go ticker