Skip to content

Instantly share code, notes, and snippets.

@guesslin
Created December 8, 2017 06:35
Show Gist options
  • Save guesslin/fcc8e1696cebc8e380cfe766373d7c40 to your computer and use it in GitHub Desktop.
Save guesslin/fcc8e1696cebc8e380cfe766373d7c40 to your computer and use it in GitHub Desktop.
/*
$ ./chanBench
Use Channel
Use Channel runs 1014856858 in 5 seconds, average 202971371 calls/s
Use Atomic
Use Channel runs 16146198617 in 5 seconds, average 3229239723 calls/s
*/
package main
import (
"fmt"
"sync/atomic"
"time"
)
func main() {
res := make(chan int)
fmt.Println("Use Channel")
m := &MyBench{end: make(chan struct{})}
go m.useChan(res)
<-time.After(time.Second * 5)
m.CloseCh()
resTimes := <-res
fmt.Printf("Use Channel runs %d in %d seconds, average %v calls/s\n", resTimes, 5, (resTimes / 5.0))
fmt.Println()
fmt.Println("Use Atomic")
go func() {
<-time.After(time.Second * 5)
m.CloseAtomic()
}()
resTimes = m.useAtomic()
fmt.Printf("Use Channel runs %d in %d seconds, average %v calls/s\n", resTimes, 5, (resTimes / 5.0))
fmt.Println()
}
type MyBench struct {
stop uint64
end chan struct{}
}
func (m *MyBench) CloseCh() {
close(m.end)
}
func (m *MyBench) CloseAtomic() {
atomic.StoreUint64(&m.stop, 1)
}
func (m *MyBench) useChan(count chan<- int) {
times := 0
for {
select {
case <-m.end:
count <- times
return
default:
times++
}
}
}
func (m *MyBench) useAtomic() int {
times := 0
for atomic.LoadUint64(&m.stop) == 0 {
times++
}
return times
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment