我尝试比较使用通道获取一个值与使用互斥锁。频道示例:
func BenchmarkNewDummy(b *testing.B) {
one := make(chan string, 1)
two := make(chan string, 1)
var wg sync.WaitGroup
wg.Add(2)
go doWork(&wg, one)
go doWork(&wg, two)
wg.Wait()
fmt.Println(<-one)
fmt.Println(<-two)
}
func doWork(wg *sync.WaitGroup, one chan string) {
defer wg.Done()
one <- "hell0"
}
命令:
go test -bench=. -benchmem -run BenchmarkNewDummy -cpuprofile cpuCh.out -memprofile memCh.prof
输出没有提供任何有用的信息
goos: darwin
goarch: amd64
BenchmarkNewDummy-8 hell0
hell0
hell0
hell0
hell0
hell0
hell0
hell0
hell0
hell0
2000000000 0.00 ns/op 0 B/op 0 allocs/op
PASS
ok 0.508s
与互斥量情况几乎相同:
func BenchmarkNewDummy(b *testing.B) {
one := ""
two := ""
var wg sync.WaitGroup
wg.Add(2)
var mu sync.Mutex
go func() {
mu.Lock()
defer mu.Unlock()
defer wg.Done()
one = "hello"
}()
go func() {
mu.Lock()
defer mu.Unlock()
defer wg.Done()
two = "hello"
}()
wg.Wait()
fmt.Println(one)
fmt.Println(two)
}
输出:
goos: darwin
goarch:
BenchmarkNewDummy-8 hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
2000000000 0.00 ns/op 0 B/op 0 allocs/op
PASS
ok 0.521s
内存图看起来几乎相同,但使用 mutext 更大的内存分配,但也没有提供信息:
是否可以比较通道和互斥体内存消耗?