英文:
How make better timeout function
问题
我正在使用time.After(time)
,它工作得很好。
我的问题是:它是否准确,我应该继续使用它还是自己编写一个函数?我正在使用它来实现Raft共识算法。
英文:
I was using time.After(time)
, which is working OK.
My question is: Is it precise and should I use this or should I make my own function? I am using this with a Raft Consensus algorithm implementation.
答案1
得分: 4
我假设你是指 time.After?
我写了一个快速的基准测试来回答这个问题。
使用 go test -run XXX -bench . time_after_test.go
运行。
package main
import (
"testing"
"time"
)
func BenchmarkTimeAfterSecond(b *testing.B) {
for i := 0; i < b.N; i++ {
<-time.After(time.Second)
}
}
func BenchmarkTimeAfterMillisecond(b *testing.B) {
for i := 0; i < b.N; i++ {
<-time.After(time.Millisecond)
}
}
func BenchmarkTimeAfterMicrosecond(b *testing.B) {
for i := 0; i < b.N; i++ {
<-time.After(time.Microsecond)
}
}
func BenchmarkTimeAfterNanosecond(b *testing.B) {
for i := 0; i < b.N; i++ {
<-time.After(time.Nanosecond)
}
}
在我的 Linux amd64 机器上,使用 go1.2 运行得到以下结果:
BenchmarkTimeAfterSecond 1 1000132210 ns/op
BenchmarkTimeAfterMillisecond 2000 1106763 ns/op
BenchmarkTimeAfterMicrosecond 50000 62649 ns/op
BenchmarkTimeAfterNanosecond 5000000 493 ns/op
所以在我的机器上,答案精确到大约 0.1-0.2 毫秒。
这个结果非常依赖于操作系统和硬件,因此在你选择的操作系统和硬件上可能会有所不同。
英文:
I presume you mean time.After?
I wrote a quick benchmark to answer this question.
Run with go test -run XXX -bench . time_after_test.go
package main
import (
"testing"
"time"
)
func BenchmarkTimeAfterSecond(b *testing.B) {
for i := 0; i < b.N; i++ {
<-time.After(time.Second)
}
}
func BenchmarkTimeAfterMillisecond(b *testing.B) {
for i := 0; i < b.N; i++ {
<-time.After(time.Millisecond)
}
}
func BenchmarkTimeAfterMicrosecond(b *testing.B) {
for i := 0; i < b.N; i++ {
<-time.After(time.Microsecond)
}
}
func BenchmarkTimeAfterNanosecond(b *testing.B) {
for i := 0; i < b.N; i++ {
<-time.After(time.Nanosecond)
}
}
This gave this under go1.2 on a linux amd64 machine
BenchmarkTimeAfterSecond 1 1000132210 ns/op
BenchmarkTimeAfterMillisecond 2000 1106763 ns/op
BenchmarkTimeAfterMicrosecond 50000 62649 ns/op
BenchmarkTimeAfterNanosecond 5000000 493 ns/op
So the answer is accurate to 0.1-0.2 mS or so on my machine.
This is extremely OS and hardware dependent though so will vary on your OS and hardware of choice.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论