Skip to content

Instantly share code, notes, and snippets.

@ja7ad
Created September 29, 2024 08:19
Show Gist options
  • Save ja7ad/dfebee1e3897eb2b291a00812238137a to your computer and use it in GitHub Desktop.
Save ja7ad/dfebee1e3897eb2b291a00812238137a to your computer and use it in GitHub Desktop.
Benchmark cbor
package bench
import (
"github.com/ugorji/go/codec"
"testing"
)
type Sample struct {
Name string
Age int
Email string
}
func BenchmarkCBOREncode(b *testing.B) {
b.ReportAllocs()
h := new(codec.CborHandle)
sampleData := Sample{Name: "Alice", Age: 30, Email: "[email protected]"}
var encodedData []byte
b.ResetTimer()
for i := 0; i < b.N; i++ {
enc := codec.NewEncoderBytes(&encodedData, h)
err := enc.Encode(sampleData)
if err != nil {
b.Fatalf("Error encoding: %v", err)
}
}
}
func BenchmarkCBORDecode(b *testing.B) {
b.ReportAllocs()
h := new(codec.CborHandle)
sampleData := Sample{Name: "Alice", Age: 30, Email: "[email protected]"}
var encodedData []byte
enc := codec.NewEncoderBytes(&encodedData, h)
err := enc.Encode(sampleData)
if err != nil {
b.Fatalf("Error encoding: %v", err)
}
var decodedData Sample
b.ResetTimer()
for i := 0; i < b.N; i++ {
dec := codec.NewDecoderBytes(encodedData, h)
err := dec.Decode(&decodedData)
if err != nil {
b.Fatalf("Error decoding: %v", err)
}
}
}
@ja7ad
Copy link
Author

ja7ad commented Sep 29, 2024

goos: linux
goarch: amd64
pkg: bench
cpu: AMD Ryzen 7 5700U with Radeon Graphics         
BenchmarkCBOREncode
BenchmarkCBOREncode-16    	 3233833	       362.6 ns/op	     272 B/op	       2 allocs/op
BenchmarkCBORDecode
BenchmarkCBORDecode-16    	 1917604	       636.7 ns/op	     605 B/op	       3 allocs/op
PASS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment