runtime_sema_test.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package sync_test
  5. import (
  6. "runtime"
  7. . "sync"
  8. "testing"
  9. )
  10. func BenchmarkSemaUncontended(b *testing.B) {
  11. type PaddedSem struct {
  12. sem uint32
  13. pad [32]uint32
  14. }
  15. b.RunParallel(func(pb *testing.PB) {
  16. sem := new(PaddedSem)
  17. for pb.Next() {
  18. Runtime_Semrelease(&sem.sem)
  19. Runtime_Semacquire(&sem.sem)
  20. }
  21. })
  22. }
  23. func benchmarkSema(b *testing.B, block, work bool) {
  24. sem := uint32(0)
  25. if block {
  26. done := make(chan bool)
  27. go func() {
  28. for p := 0; p < runtime.GOMAXPROCS(0)/2; p++ {
  29. Runtime_Semacquire(&sem)
  30. }
  31. done <- true
  32. }()
  33. defer func() {
  34. <-done
  35. }()
  36. }
  37. b.RunParallel(func(pb *testing.PB) {
  38. foo := 0
  39. for pb.Next() {
  40. Runtime_Semrelease(&sem)
  41. if work {
  42. for i := 0; i < 100; i++ {
  43. foo *= 2
  44. foo /= 2
  45. }
  46. }
  47. Runtime_Semacquire(&sem)
  48. }
  49. _ = foo
  50. Runtime_Semrelease(&sem)
  51. })
  52. }
  53. func BenchmarkSemaSyntNonblock(b *testing.B) {
  54. benchmarkSema(b, false, false)
  55. }
  56. func BenchmarkSemaSyntBlock(b *testing.B) {
  57. benchmarkSema(b, true, false)
  58. }
  59. func BenchmarkSemaWorkNonblock(b *testing.B) {
  60. benchmarkSema(b, false, true)
  61. }
  62. func BenchmarkSemaWorkBlock(b *testing.B) {
  63. benchmarkSema(b, true, true)
  64. }