Skip to content

Instantly share code, notes, and snippets.

@roustem
Created October 12, 2018 17:04
Show Gist options
  • Save roustem/d6428002d2095446d924522a3c1cd079 to your computer and use it in GitHub Desktop.
Save roustem/d6428002d2095446d924522a3c1cd079 to your computer and use it in GitHub Desktop.
package main
import (
"sync/atomic"
"testing"
)
var id uint64
const chanLength = 100
var idChan = make(chan uint64, chanLength)
func nextIDAtomic() uint64 {
return atomic.AddUint64(&id, 1)
}
func nextIDChan() uint64 {
if len(idChan) == 0 {
for i := 0; i < chanLength; i++ {
idChan <- id
id++
}
}
return <-idChan
}
func BenchmarkNextIDAtomic(b *testing.B) {
for n := 0; n < b.N; n++ {
nextIDAtomic()
}
}
func BenchmarkNextIDChan(b *testing.B) {
for n := 0; n < b.N; n++ {
nextIDChan()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment