diff options
Diffstat (limited to 'libgo/go/testing/benchmark_test.go')
-rw-r--r-- | libgo/go/testing/benchmark_test.go | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/libgo/go/testing/benchmark_test.go b/libgo/go/testing/benchmark_test.go index 94e994dfae0..9997b992042 100644 --- a/libgo/go/testing/benchmark_test.go +++ b/libgo/go/testing/benchmark_test.go @@ -5,7 +5,11 @@ package testing_test import ( + "bytes" + "runtime" + "sync/atomic" "testing" + "text/template" ) var roundDownTests = []struct { @@ -56,3 +60,53 @@ func TestRoundUp(t *testing.T) { } } } + +func TestRunParallel(t *testing.T) { + testing.Benchmark(func(b *testing.B) { + procs := uint32(0) + iters := uint64(0) + b.SetParallelism(3) + b.RunParallel(func(pb *testing.PB) { + atomic.AddUint32(&procs, 1) + for pb.Next() { + atomic.AddUint64(&iters, 1) + } + }) + if want := uint32(3 * runtime.GOMAXPROCS(0)); procs != want { + t.Errorf("got %v procs, want %v", procs, want) + } + if iters != uint64(b.N) { + t.Errorf("got %v iters, want %v", iters, b.N) + } + }) +} + +func TestRunParallelFail(t *testing.T) { + testing.Benchmark(func(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + // The function must be able to log/abort + // w/o crashing/deadlocking the whole benchmark. + b.Log("log") + b.Error("error") + b.Fatal("fatal") + }) + }) +} + +func ExampleB_RunParallel() { + // Parallel benchmark for text/template.Template.Execute on a single object. + testing.Benchmark(func(b *testing.B) { + templ := template.Must(template.New("test").Parse("Hello, {{.}}!")) + // RunParallel will create GOMAXPROCS goroutines + // and distribute work among them. + b.RunParallel(func(pb *testing.PB) { + // Each goroutine has its own bytes.Buffer. + var buf bytes.Buffer + for pb.Next() { + // The loop body is executed b.N times total across all goroutines. + buf.Reset() + templ.Execute(&buf, "World") + } + }) + }) +} |