Skip to content

Instantly share code, notes, and snippets.

@draveness
Created July 11, 2019 15:07
Show Gist options
  • Save draveness/a3d0921d8d49736401a1287a18c0f337 to your computer and use it in GitHub Desktop.
Save draveness/a3d0921d8d49736401a1287a18c0f337 to your computer and use it in GitHub Desktop.
Benchmark Golang Timers
package main
import (
"fmt"
"sort"
"sync"
"testing"
"time"
)
func TestTimers(t *testing.T) {
for _, count := range []int{1000, 2000, 5000, 10000, 20000, 50000, 100000, 500000} {
runTimers(count)
}
}
func runTimers(count int) {
durationCh := make(chan time.Duration, count)
wg := sync.WaitGroup{}
wg.Add(count)
for i := 0; i < count; i++ {
go func() {
startedAt := time.Now()
time.AfterFunc(10*time.Millisecond, func() {
defer wg.Done()
durationCh <- time.Since(startedAt)
})
}()
}
wg.Wait()
close(durationCh)
durations := []time.Duration{}
totalDuration := 0 * time.Millisecond
for duration := range durationCh {
durations = append(durations, duration)
totalDuration += duration
}
averageDuration := totalDuration / time.Duration(count)
sort.Slice(durations, func(i, j int) bool {
return durations[i] < durations[j]
})
fmt.Printf("run %v timers with average=%v, pct50=%v, pct99=%v\n", count, averageDuration, durations[count/2], durations[int(float64(count)*0.99)])
}
@draveness
Copy link
Author

$ go test ./... -v
=== RUN   TestTimers
run 1000 timers with average=10.367111ms, pct50=10.234219ms, pct99=10.913219ms
run 2000 timers with average=10.431598ms, pct50=10.37367ms, pct99=11.025823ms
run 5000 timers with average=11.873773ms, pct50=11.986249ms, pct99=12.673725ms
run 10000 timers with average=11.954716ms, pct50=12.313613ms, pct99=13.507858ms
run 20000 timers with average=11.456237ms, pct50=10.625529ms, pct99=25.246254ms
run 50000 timers with average=21.223818ms, pct50=14.792982ms, pct99=34.250143ms
run 100000 timers with average=36.010924ms, pct50=31.794761ms, pct99=128.089527ms
run 500000 timers with average=176.676498ms, pct50=138.238588ms, pct99=676.967558ms
--- PASS: TestTimers (1.21s)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment