Home | History | Annotate | Download | only in sync
      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 
      5 package sync_test
      6 
      7 import (
      8 	"runtime"
      9 	. "sync"
     10 	"testing"
     11 )
     12 
     13 func BenchmarkSemaUncontended(b *testing.B) {
     14 	type PaddedSem struct {
     15 		sem uint32
     16 		pad [32]uint32
     17 	}
     18 	b.RunParallel(func(pb *testing.PB) {
     19 		sem := new(PaddedSem)
     20 		for pb.Next() {
     21 			Runtime_Semrelease(&sem.sem)
     22 			Runtime_Semacquire(&sem.sem)
     23 		}
     24 	})
     25 }
     26 
     27 func benchmarkSema(b *testing.B, block, work bool) {
     28 	sem := uint32(0)
     29 	if block {
     30 		done := make(chan bool)
     31 		go func() {
     32 			for p := 0; p < runtime.GOMAXPROCS(0)/2; p++ {
     33 				Runtime_Semacquire(&sem)
     34 			}
     35 			done <- true
     36 		}()
     37 		defer func() {
     38 			<-done
     39 		}()
     40 	}
     41 	b.RunParallel(func(pb *testing.PB) {
     42 		foo := 0
     43 		for pb.Next() {
     44 			Runtime_Semrelease(&sem)
     45 			if work {
     46 				for i := 0; i < 100; i++ {
     47 					foo *= 2
     48 					foo /= 2
     49 				}
     50 			}
     51 			Runtime_Semacquire(&sem)
     52 		}
     53 		_ = foo
     54 		Runtime_Semrelease(&sem)
     55 	})
     56 }
     57 
     58 func BenchmarkSemaSyntNonblock(b *testing.B) {
     59 	benchmarkSema(b, false, false)
     60 }
     61 
     62 func BenchmarkSemaSyntBlock(b *testing.B) {
     63 	benchmarkSema(b, true, false)
     64 }
     65 
     66 func BenchmarkSemaWorkNonblock(b *testing.B) {
     67 	benchmarkSema(b, false, true)
     68 }
     69 
     70 func BenchmarkSemaWorkBlock(b *testing.B) {
     71 	benchmarkSema(b, true, true)
     72 }
     73