2021-05-18 10:43:13 +03:00
|
|
|
// Copyright 2021 Andy Pan & Dietoad. All rights reserved.
|
|
|
|
// Use of this source code is governed by an MIT-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package internal
|
|
|
|
|
|
|
|
import (
|
|
|
|
"runtime"
|
|
|
|
"sync"
|
|
|
|
"sync/atomic"
|
|
|
|
"testing"
|
|
|
|
)
|
|
|
|
|
2021-06-22 13:06:51 +03:00
|
|
|
/*
|
|
|
|
Benchmark result for three types of locks:
|
|
|
|
goos: darwin
|
|
|
|
goarch: amd64
|
2022-12-12 17:14:58 +03:00
|
|
|
pkg: git.internal/re/ants/v2/internal
|
2021-06-22 13:06:51 +03:00
|
|
|
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
|
|
|
|
BenchmarkMutex-12 20549502 71.84 ns/op 0 B/op 0 allocs/op
|
|
|
|
BenchmarkSpinLock-12 58629697 20.02 ns/op 0 B/op 0 allocs/op
|
|
|
|
BenchmarkBackOffSpinLock-12 72523454 15.74 ns/op 0 B/op 0 allocs/op
|
|
|
|
*/
|
|
|
|
|
2021-05-18 10:43:13 +03:00
|
|
|
type originSpinLock uint32
|
|
|
|
|
|
|
|
func (sl *originSpinLock) Lock() {
|
|
|
|
for !atomic.CompareAndSwapUint32((*uint32)(sl), 0, 1) {
|
|
|
|
runtime.Gosched()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (sl *originSpinLock) Unlock() {
|
|
|
|
atomic.StoreUint32((*uint32)(sl), 0)
|
|
|
|
}
|
|
|
|
|
2021-11-27 15:21:45 +03:00
|
|
|
func NewOriginSpinLock() sync.Locker {
|
2021-05-18 10:43:13 +03:00
|
|
|
return new(originSpinLock)
|
|
|
|
}
|
|
|
|
|
|
|
|
func BenchmarkMutex(b *testing.B) {
|
|
|
|
m := sync.Mutex{}
|
|
|
|
b.RunParallel(func(pb *testing.PB) {
|
|
|
|
for pb.Next() {
|
|
|
|
m.Lock()
|
2021-05-18 11:09:23 +03:00
|
|
|
//nolint:staticcheck
|
2021-05-18 10:43:13 +03:00
|
|
|
m.Unlock()
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func BenchmarkSpinLock(b *testing.B) {
|
2021-11-27 15:21:45 +03:00
|
|
|
spin := NewOriginSpinLock()
|
2021-05-18 10:43:13 +03:00
|
|
|
b.RunParallel(func(pb *testing.PB) {
|
|
|
|
for pb.Next() {
|
|
|
|
spin.Lock()
|
2021-05-18 11:09:23 +03:00
|
|
|
//nolint:staticcheck
|
2021-05-18 10:43:13 +03:00
|
|
|
spin.Unlock()
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func BenchmarkBackOffSpinLock(b *testing.B) {
|
2021-11-27 15:21:45 +03:00
|
|
|
spin := NewSpinLock()
|
2021-05-18 10:43:13 +03:00
|
|
|
b.RunParallel(func(pb *testing.PB) {
|
|
|
|
for pb.Next() {
|
|
|
|
spin.Lock()
|
2021-05-18 11:09:23 +03:00
|
|
|
//nolint:staticcheck
|
2021-05-18 10:43:13 +03:00
|
|
|
spin.Unlock()
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|