package main | |
import ( | |
"fmt" | |
"runtime" | |
"sync" | |
"testing" | |
) | |
type ChMutex struct { | |
wait chan int | |
} | |
func (m *ChMutex) Lock() { | |
if m.wait == nil { | |
m.wait = make(chan int, 1) | |
m.wait <- 1 | |
} | |
<-m.wait | |
} | |
func (m *ChMutex) Unlock() { | |
if m.wait == nil { | |
panic("until locked") | |
} | |
m.wait <- 1 | |
} | |
type ICounter interface { | |
Incr() | |
Count() int | |
} | |
type Counter struct { | |
count int | |
} | |
func (c *Counter) Incr() { | |
c.count++ | |
} | |
func (c *Counter) Count() int { | |
return c.count | |
} | |
type MutexCounter struct { | |
Counter | |
sync.Mutex | |
} | |
func (c *MutexCounter) Incr() { | |
c.Mutex.Lock() | |
defer c.Mutex.Unlock() | |
c.Counter.Incr() | |
} | |
type ChMutexCounter struct { | |
Counter | |
ChMutex | |
} | |
func (c *ChMutexCounter) Incr() { | |
c.ChMutex.Lock() | |
defer c.ChMutex.Unlock() | |
c.Counter.Incr() | |
} | |
func incr(procs, maxNum int, c ICounter) { | |
runtime.GOMAXPROCS(procs) | |
wait := make(chan int) | |
go func() { | |
for i := 0; i < maxNum; i++ { | |
c.Incr() | |
} | |
wait <- 1 | |
}() | |
go func() { | |
for i := 0; i < maxNum; i++ { | |
c.Incr() | |
} | |
wait <- 1 | |
}() | |
<-wait | |
<-wait | |
fmt.Printf("GOMAXPROCS=%d expect=%d num=%d\n", procs, maxNum*2, c.Count()) | |
} | |
func BenchmarkCounterProcs1(b *testing.B) { | |
incr(1, b.N, &Counter{0}) | |
} | |
func BenchmarkCounterProcs2(b *testing.B) { | |
incr(2, b.N, &Counter{0}) | |
} | |
func BenchmarkMutexCounterProcs1(b *testing.B) { | |
incr(1, b.N, &MutexCounter{Counter{0}, sync.Mutex{}}) | |
} | |
func BenchmarkMutexCounterProcs2(b *testing.B) { | |
incr(2, b.N, &MutexCounter{Counter{0}, sync.Mutex{}}) | |
} | |
func BenchmarkChMutexCounterProcs1(b *testing.B) { | |
incr(1, b.N, &ChMutexCounter{Counter{0}, ChMutex{}}) | |
} | |
func BenchmarkChMutexCounterProcs2(b *testing.B) { | |
incr(2, b.N, &ChMutexCounter{Counter{0}, ChMutex{}}) | |
} |
This comment has been minimized.
This comment has been minimized.
$ go test -bench .
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
$ go test -bench .