blob: 0da0c3f1d4e6878c633468cad246d56861714b12 [file] [log] [blame]
Jiri Simsad7616c92015-03-24 23:44:30 -07001// Copyright 2015 The Vanadium 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
Jungho Ahnfa7a31f2015-01-07 17:34:12 -08005package benchmark
6
7import (
8 "bytes"
9 "fmt"
10 "io"
11 "os"
12 "regexp"
Cosmos Nicolaoue35c92f2015-08-24 16:22:00 -070013 "runtime"
Jungho Ahnfa7a31f2015-01-07 17:34:12 -080014 "strings"
15 "testing"
16 "time"
17)
18
19func BenchmarkTest(b *testing.B) {
20 stats := AddStats(b, 0)
21 for i := 1; i <= b.N; i++ {
22 time.Sleep(1 * time.Microsecond)
23 stats.Add(time.Duration(i) * time.Microsecond)
24 }
25}
26
27func BenchmarkTestMulti(b *testing.B) {
28 stats1 := AddStatsWithName(b, "S1", 0)
29 stats2 := AddStatsWithName(b, "S2", 0)
30 for i := 1; i <= b.N; i++ {
31 time.Sleep(1 * time.Microsecond)
32 stats1.Add(time.Duration(i) * time.Microsecond)
33 stats2.Add(time.Duration(i) * time.Millisecond)
34 }
35}
36
Cosmos Nicolaoue35c92f2015-08-24 16:22:00 -070037func benchmarkName(name string) string {
38 procs := runtime.GOMAXPROCS(-1)
39 if procs != 1 {
40 return fmt.Sprintf("%s-%d", name, procs)
41 }
42 return name
43}
44
Jungho Ahnfa7a31f2015-01-07 17:34:12 -080045func TestStatsInjection(t *testing.T) {
46 stdout := os.Stdout
47 r, w, _ := os.Pipe()
48 os.Stdout = w
49
50 outC := make(chan string)
51 go func() {
52 b := new(bytes.Buffer)
53 io.Copy(b, r)
54 r.Close()
55 outC <- b.String()
56 }()
57
58 startStatsInjector()
59
Cosmos Nicolaoue35c92f2015-08-24 16:22:00 -070060 fmt.Printf("%s\t", benchmarkName("BenchmarkTest"))
Jungho Ahnfa7a31f2015-01-07 17:34:12 -080061 result := testing.Benchmark(BenchmarkTest)
62 fmt.Println(result.String())
63
Cosmos Nicolaoue35c92f2015-08-24 16:22:00 -070064 fmt.Printf("%s\t", benchmarkName("BenchmarkTestMulti"))
Jungho Ahnfa7a31f2015-01-07 17:34:12 -080065 result = testing.Benchmark(BenchmarkTestMulti)
66 fmt.Println(result.String())
67
68 stopStatsInjector()
69
70 w.Close()
71 os.Stdout = stdout
72 out := <-outC
73
74 if strings.Count(out, "Histogram") != 3 {
75 t.Errorf("unexpected stats output:\n%s", out)
76 }
77 if matched, _ := regexp.MatchString("Histogram.*\\)\n", out); !matched {
78 t.Errorf("unnamed stats not found:\n%s", out)
79 }
80 if matched, _ := regexp.MatchString("Histogram.*\\): S1\n", out); !matched {
81 t.Errorf("stats S1 not found:\n%s", out)
82 }
83 if matched, _ := regexp.MatchString("Histogram.*\\): S2\n", out); !matched {
84 t.Errorf("stats S2 not found:\n%s", out)
85 }
86}