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.
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.