如何改进超时函数的实现?

huangapple go评论97阅读模式
英文:

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 (
	&quot;testing&quot;
	&quot;time&quot;
)

func BenchmarkTimeAfterSecond(b *testing.B) {
	for i := 0; i &lt; b.N; i++ {
		&lt;-time.After(time.Second)
	}
}

func BenchmarkTimeAfterMillisecond(b *testing.B) {
	for i := 0; i &lt; b.N; i++ {
		&lt;-time.After(time.Millisecond)
	}
}

func BenchmarkTimeAfterMicrosecond(b *testing.B) {
	for i := 0; i &lt; b.N; i++ {
		&lt;-time.After(time.Microsecond)
	}
}

func BenchmarkTimeAfterNanosecond(b *testing.B) {
	for i := 0; i &lt; b.N; i++ {
		&lt;-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.

huangapple
  • 本文由 发表于 2014年3月8日 15:21:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/22266401.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定