5
0
mirror of https://github.com/cwinfo/yggdrasil-go.git synced 2024-11-30 00:51:36 +00:00
yggdrasil-go/misc/tests/pool.go

90 lines
1.5 KiB
Go
Raw Normal View History

2017-12-29 04:16:20 +00:00
package main
import "fmt"
2018-01-04 22:37:51 +00:00
2017-12-29 04:16:20 +00:00
//import "net"
import "time"
import "runtime"
import "sync/atomic"
func poolbench() {
2018-01-04 22:37:51 +00:00
nWorkers := runtime.GOMAXPROCS(0)
work := make(chan func(), 1)
workers := make(chan chan<- func(), nWorkers)
makeWorker := func() chan<- func() {
ch := make(chan func())
go func() {
for {
f := <-ch
f()
select {
case workers <- (ch):
default:
return
}
}
}()
return ch
}
getWorker := func() chan<- func() {
select {
case ch := <-workers:
return ch
default:
return makeWorker()
}
}
dispatcher := func() {
for {
w := <-work
ch := getWorker()
ch <- w
}
}
go dispatcher()
var count uint64
const nCounts = 1000000
for idx := 0; idx < nCounts; idx++ {
f := func() { atomic.AddUint64(&count, 1) }
work <- f
}
for atomic.LoadUint64(&count) < nCounts {
}
2017-12-29 04:16:20 +00:00
}
func normalbench() {
2018-01-04 22:37:51 +00:00
var count uint64
const nCounts = 1000000
ch := make(chan struct{}, 1)
ch <- struct{}{}
for idx := 0; idx < nCounts; idx++ {
f := func() { atomic.AddUint64(&count, 1) }
f()
<-ch
ch <- struct{}{}
}
2017-12-29 04:16:20 +00:00
}
func gobench() {
2018-01-04 22:37:51 +00:00
var count uint64
const nCounts = 1000000
for idx := 0; idx < nCounts; idx++ {
f := func() { atomic.AddUint64(&count, 1) }
go f()
}
for atomic.LoadUint64(&count) < nCounts {
}
2017-12-29 04:16:20 +00:00
}
func main() {
2018-01-04 22:37:51 +00:00
start := time.Now()
poolbench()
fmt.Println(time.Since(start))
start = time.Now()
normalbench()
fmt.Println(time.Since(start))
start = time.Now()
gobench()
fmt.Println(time.Since(start))
2017-12-29 04:16:20 +00:00
}