| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
// This file contains helper functions regarding compression/decompression for confighttp. |
| 5 |
|
| 6 |
package confighttp // import "go.opentelemetry.io/collector/config/confighttp" |
| 7 |
|
| 8 |
import ( |
| 9 |
"bytes" |
| 10 |
"fmt" |
| 11 |
"io" |
| 12 |
"strings" |
| 13 |
"testing" |
| 14 |
|
| 15 |
"github.com/klauspost/compress/zstd" |
| 16 |
"github.com/stretchr/testify/require" |
| 17 |
|
| 18 |
"go.opentelemetry.io/collector/config/configcompression" |
| 19 |
) |
| 20 |
|
| 21 |
func BenchmarkCompression(b *testing.B) { |
| 22 |
benchmarks := []struct { |
| 23 |
codec configcompression.Type |
| 24 |
name string |
| 25 |
function func(*testing.B, configcompression.Type, *bytes.Buffer, []byte) |
| 26 |
}{ |
| 27 |
{ |
| 28 |
codec: configcompression.TypeZstd, |
| 29 |
name: "zstdWithConcurrency", |
| 30 |
function: benchmarkCompression, |
| 31 |
}, |
| 32 |
{ |
| 33 |
codec: configcompression.TypeZstd, |
| 34 |
name: "zstdNoConcurrency", |
| 35 |
function: benchmarkCompressionNoConcurrency, |
| 36 |
}, |
| 37 |
} |
| 38 |
payload := make([]byte, 10<<22) |
| 39 |
buffer := bytes.Buffer{} |
| 40 |
buffer.Grow(len(payload)) |
| 41 |
|
| 42 |
ts := &bytes.Buffer{} |
| 43 |
defer func() { |
| 44 |
fmt.Printf("input => %.2f MB\n", float64(len(payload))/(1024*1024)) |
| 45 |
fmt.Println(ts) |
| 46 |
}() |
| 47 |
|
| 48 |
for i := range benchmarks { |
| 49 |
benchmark := &benchmarks[i] |
| 50 |
b.Run(benchmark.name, func(b *testing.B) { |
| 51 |
benchmark.function(b, benchmark.codec, &buffer, payload) |
| 52 |
}) |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
func benchmarkCompression(b *testing.B, _ configcompression.Type, buf *bytes.Buffer, payload []byte) { |
| 57 |
// Concurrency Enabled |
| 58 |
stringReader := strings.NewReader(string(payload)) |
| 59 |
stringReadCloser := io.NopCloser(stringReader) |
| 60 |
var enc io.Writer |
| 61 |
b.ResetTimer() |
| 62 |
b.ReportAllocs() |
| 63 |
b.SetBytes(int64(len(payload))) |
| 64 |
for b.Loop() { |
| 65 |
enc, _ = zstd.NewWriter(nil, zstd.WithEncoderConcurrency(5)) |
| 66 |
enc.(writeCloserReset).Reset(buf) |
| 67 |
_, copyErr := io.Copy(enc, stringReadCloser) |
| 68 |
require.NoError(b, copyErr) |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
func benchmarkCompressionNoConcurrency(b *testing.B, _ configcompression.Type, buf *bytes.Buffer, payload []byte) { |
| 73 |
stringReader := strings.NewReader(string(payload)) |
| 74 |
stringReadCloser := io.NopCloser(stringReader) |
| 75 |
var enc io.Writer |
| 76 |
b.ResetTimer() |
| 77 |
b.ReportAllocs() |
| 78 |
b.SetBytes(int64(len(payload))) |
| 79 |
for b.Loop() { |
| 80 |
enc, _ = zstd.NewWriter(nil, zstd.WithEncoderConcurrency(1)) |
| 81 |
enc.(writeCloserReset).Reset(buf) |
| 82 |
_, copyErr := io.Copy(enc, stringReadCloser) |
| 83 |
require.NoError(b, copyErr) |
| 84 |
} |
| 85 |
} |