Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve performance of trace id generation #977

Merged
merged 2 commits into from
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions v3/internal/trace_id_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
package internal

import (
"encoding/hex"
"math/rand"
"sync"
)
Expand Down Expand Up @@ -39,6 +38,10 @@ const (
maxIDByteLen = 16
)

const (
hextable = "0123456789abcdef"
)

// GenerateTraceID creates a new trace identifier, which is a 32 character hex string.
func (tg *TraceIDGenerator) GenerateTraceID() string {
return tg.generateID(traceIDByteLen)
Expand All @@ -50,9 +53,15 @@ func (tg *TraceIDGenerator) GenerateSpanID() string {
}

func (tg *TraceIDGenerator) generateID(len int) string {
var bits [maxIDByteLen]byte
var bits [maxIDByteLen * 2]byte
tg.Lock()
defer tg.Unlock()
tg.rnd.Read(bits[:len])
return hex.EncodeToString(bits[:len])

// In-place encode
for i := len - 1; i >= 0; i-- {
bits[i*2+1] = hextable[bits[i]&0x0f]
bits[i*2] = hextable[bits[i]>>4]
}
return string(bits[:len*2])
}
15 changes: 15 additions & 0 deletions v3/internal/trace_id_generator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,18 @@ func BenchmarkTraceIDGenerator(b *testing.B) {
}
}
}

func BenchmarkTraceIDGeneratorParallel(b *testing.B) {
tg := NewTraceIDGenerator(12345)

b.ResetTimer()
b.ReportAllocs()

b.RunParallel(func(p *testing.PB) {
for p.Next() {
if id := tg.GenerateSpanID(); id == "" {
b.Fatal(id)
}
}
})
}
Loading