[go语言]Buffered channel、slice和mutex的简单性能测试
测试代码:
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
const COUNT = 1000000
func bench1(ch chan int) time.Duration {
t := time.Now()
for i := 0; i < COUNT; i++ {
ch <- i
}
var v int
for i := 0; i < COUNT; i++ {
v = <-ch
}
_ = v
return time.Now().Sub(t)
}
func bench2(s []int) time.Duration {
t := time.Now()
for i := 0; i < COUNT; i++ {
s[i] = i
}
var v int
for i := 0; i < COUNT; i++ {
v = s[i]
}
_ = v
return time.Now().Sub(t)
}
func bench3(s []int, mutex *sync.Mutex) time.Duration {
t := time.Now()
for i := 0; i < COUNT; i++ {
mutex.Lock()
s[i] = i
mutex.Unlock()
}
var v int
for i := 0; i < COUNT; i++ {
mutex.Lock()
v = s[i]
mutex.Unlock()
}
_ = v
return time.Now().Sub(t)
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
ch := make(chan int, COUNT)
s := make([]int, COUNT)
var mutex sync.Mutex
fmt.Println("channel\tslice\tmutex_slice")
for i := 0; i < 10; i++ {
fmt.Printf("%v\t%v\t%v\n", bench1(ch), bench2(s), bench3(s, &mutex))
}
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。