Rebase.
[official-gcc.git] / libgo / go / testing / benchmark_test.go
blobf7ea64e7f1c89076acada85c27e01739e8c288f9
1 // Copyright 2013 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.
5 package testing_test
7 import (
8 "bytes"
9 "runtime"
10 "sync/atomic"
11 "testing"
12 "text/template"
15 var roundDownTests = []struct {
16 v, expected int
18 {1, 1},
19 {9, 1},
20 {10, 10},
21 {11, 10},
22 {100, 100},
23 {101, 100},
24 {999, 100},
25 {1000, 1000},
26 {1001, 1000},
29 func TestRoundDown10(t *testing.T) {
30 for _, tt := range roundDownTests {
31 actual := testing.RoundDown10(tt.v)
32 if tt.expected != actual {
33 t.Errorf("roundDown10(%d): expected %d, actual %d", tt.v, tt.expected, actual)
38 var roundUpTests = []struct {
39 v, expected int
41 {0, 1},
42 {1, 1},
43 {2, 2},
44 {5, 5},
45 {9, 10},
46 {999, 1000},
47 {1000, 1000},
48 {1400, 2000},
49 {1700, 2000},
50 {4999, 5000},
51 {5000, 5000},
52 {5001, 10000},
55 func TestRoundUp(t *testing.T) {
56 for _, tt := range roundUpTests {
57 actual := testing.RoundUp(tt.v)
58 if tt.expected != actual {
59 t.Errorf("roundUp(%d): expected %d, actual %d", tt.v, tt.expected, actual)
64 func TestRunParallel(t *testing.T) {
65 testing.Benchmark(func(b *testing.B) {
66 procs := uint32(0)
67 iters := uint64(0)
68 b.SetParallelism(3)
69 b.RunParallel(func(pb *testing.PB) {
70 atomic.AddUint32(&procs, 1)
71 for pb.Next() {
72 atomic.AddUint64(&iters, 1)
75 if want := uint32(3 * runtime.GOMAXPROCS(0)); procs != want {
76 t.Errorf("got %v procs, want %v", procs, want)
78 if iters != uint64(b.N) {
79 t.Errorf("got %v iters, want %v", iters, b.N)
84 func TestRunParallelFail(t *testing.T) {
85 testing.Benchmark(func(b *testing.B) {
86 b.RunParallel(func(pb *testing.PB) {
87 // The function must be able to log/abort
88 // w/o crashing/deadlocking the whole benchmark.
89 b.Log("log")
90 b.Error("error")
95 func ExampleB_RunParallel() {
96 // Parallel benchmark for text/template.Template.Execute on a single object.
97 testing.Benchmark(func(b *testing.B) {
98 templ := template.Must(template.New("test").Parse("Hello, {{.}}!"))
99 // RunParallel will create GOMAXPROCS goroutines
100 // and distribute work among them.
101 b.RunParallel(func(pb *testing.PB) {
102 // Each goroutine has its own bytes.Buffer.
103 var buf bytes.Buffer
104 for pb.Next() {
105 // The loop body is executed b.N times total across all goroutines.
106 buf.Reset()
107 templ.Execute(&buf, "World")