Created
January 15, 2018 13:54
-
-
Save wrfly/63f56519020494d68aebc9fad713daa5 to your computer and use it in GitHub Desktop.
compare channel and atomic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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