Skip to content

Commit

Permalink
Add a benchmark for histogram allocations (#3635)
Browse files Browse the repository at this point in the history
Co-authored-by: Chester Cheung <cheung.zhy.csu@gmail.com>
  • Loading branch information
MadVikingGod and hanyuancheung authored Feb 2, 2023
1 parent aa51224 commit 5e8eb85
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions sdk/metric/benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@ package metric // import "go.opentelemetry.io/otel/sdk/metric"

import (
"context"
"fmt"
"testing"

"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric/instrument"
"go.opentelemetry.io/otel/sdk/metric/metricdata"
)

func benchCounter(b *testing.B, views ...View) (context.Context, Reader, instrument.Int64Counter) {
Expand Down Expand Up @@ -105,3 +107,43 @@ func BenchmarkCounterCollectTenAttrs(b *testing.B) {
_, _ = rdr.Collect(ctx)
}
}

func BenchmarkCollectHistograms(b *testing.B) {
b.Run("1", benchCollectHistograms(1))
b.Run("5", benchCollectHistograms(5))
b.Run("10", benchCollectHistograms(10))
b.Run("25", benchCollectHistograms(25))
}

func benchCollectHistograms(count int) func(*testing.B) {
ctx := context.Background()
r := NewManualReader()
mtr := NewMeterProvider(
WithReader(r),
).Meter("sdk/metric/bench/histogram")

for i := 0; i < count; i++ {
name := fmt.Sprintf("fake data %d", i)
h, _ := mtr.Int64Histogram(name)

h.Record(ctx, 1)
}

// Store bechmark results in a closure to prevent the compiler from
// inlining and skipping the function.
var (
collectedMetrics metricdata.ResourceMetrics
)

return func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()

for n := 0; n < b.N; n++ {
collectedMetrics, _ = r.Collect(ctx)
if len(collectedMetrics.ScopeMetrics[0].Metrics) != count {
b.Fatalf("got %d metrics, want %d", len(collectedMetrics.ScopeMetrics[0].Metrics), count)
}
}
}
}

0 comments on commit 5e8eb85

Please sign in to comment.