Skip to content

Instantly share code, notes, and snippets.

@wrfly
Created January 15, 2018 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wrfly/63f56519020494d68aebc9fad713daa5 to your computer and use it in GitHub Desktop.
Save wrfly/63f56519020494d68aebc9fad713daa5 to your computer and use it in GitHub Desktop.
compare channel and atomic
/*
2018/01/15 21:53:31 put testing
2018/01/15 21:53:34 channel used: 2.570561041
2018/01/15 21:53:34 atomic used: 0.505121807
2018/01/15 21:53:34 take testing
2018/01/15 21:53:37 channel used: 2.329268454
2018/01/15 21:53:37 atomic used: 0.498186081
*/
package main
import (
"log"
"sync/atomic"
"time"
)
func main() {
log.Println("put testing")
num := int(1e8)
var (
start time.Time
)
C := make(chan struct{}, num)
start = time.Now()
for i := 0; i < num; i++ {
C <- struct{}{}
}
log.Println("channel used:", time.Now().Sub(start).Seconds())
start = time.Now()
var n int64
for i := 0; i < num; i++ {
atomic.AddInt64(&n, 1)
}
log.Println("atomic used:", time.Now().Sub(start).Seconds())
log.Println("take testing")
start = time.Now()
for i := 0; i < num; i++ {
<-C
}
log.Println("channel used:", time.Now().Sub(start).Seconds())
start = time.Now()
for i := 0; i < num; i++ {
atomic.AddInt64(&n, -1)
}
log.Println("atomic used:", time.Now().Sub(start).Seconds())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment