1// Copyright 2018, OpenCensus Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15
16package view
17
18import (
19	"context"
20	"fmt"
21	"testing"
22	"time"
23
24	"go.opencensus.io/stats"
25	"go.opencensus.io/tag"
26)
27
28var (
29	m     = stats.Float64("m", "", "")
30	k1, _ = tag.NewKey("k1")
31	k2, _ = tag.NewKey("k2")
32	k3, _ = tag.NewKey("k3")
33	k4, _ = tag.NewKey("k4")
34	k5, _ = tag.NewKey("k5")
35	k6, _ = tag.NewKey("k6")
36	k7, _ = tag.NewKey("k7")
37	k8, _ = tag.NewKey("k8")
38	view  = &View{
39		Measure:     m,
40		Aggregation: Distribution(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
41		TagKeys:     []tag.Key{k1, k2},
42	}
43)
44
45// BenchmarkRecordReqCommand benchmarks calling the internal recording machinery
46// directly.
47func BenchmarkRecordReqCommand(b *testing.B) {
48	w := newWorker()
49
50	register := &registerViewReq{views: []*View{view}, err: make(chan error, 1)}
51	register.handleCommand(w)
52	if err := <-register.err; err != nil {
53		b.Fatal(err)
54	}
55
56	const tagCount = 10
57	ctxs := make([]context.Context, 0, tagCount)
58	for i := 0; i < tagCount; i++ {
59		ctx, _ := tag.New(context.Background(),
60			tag.Upsert(k1, fmt.Sprintf("v%d", i)),
61			tag.Upsert(k2, fmt.Sprintf("v%d", i)),
62			tag.Upsert(k3, fmt.Sprintf("v%d", i)),
63			tag.Upsert(k4, fmt.Sprintf("v%d", i)),
64			tag.Upsert(k5, fmt.Sprintf("v%d", i)),
65			tag.Upsert(k6, fmt.Sprintf("v%d", i)),
66			tag.Upsert(k7, fmt.Sprintf("v%d", i)),
67			tag.Upsert(k8, fmt.Sprintf("v%d", i)),
68		)
69		ctxs = append(ctxs, ctx)
70	}
71
72	b.ReportAllocs()
73	b.ResetTimer()
74
75	for i := 0; i < b.N; i++ {
76		record := &recordReq{
77			ms: []stats.Measurement{
78				m.M(1),
79				m.M(1),
80				m.M(1),
81				m.M(1),
82				m.M(1),
83				m.M(1),
84				m.M(1),
85				m.M(1),
86			},
87			tm: tag.FromContext(ctxs[i%len(ctxs)]),
88			t:  time.Now(),
89		}
90		record.handleCommand(w)
91	}
92}
93