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

fix: Optimize span and trace ID generation #1521

Merged
merged 2 commits into from
Sep 13, 2023
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
48 changes: 48 additions & 0 deletions api/benchmarks/id_generation_bench.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# frozen_string_literal: true

# Copyright The OpenTelemetry Authors
#
# SPDX-License-Identifier: Apache-2.0

require 'benchmark/ipsa'

INVALID_SPAN_ID = ("\0" * 8).b
INVALID_TRACE_ID = ("\0" * 16).b

def generate_trace_id
loop do
id = Random.bytes(16)
return id unless id == INVALID_TRACE_ID
end
end

def generate_trace_id_while
id = Random.bytes(16)
id = Random.bytes(16) while id == INVALID_TRACE_ID
id
end

def generate_span_id
loop do
id = Random.bytes(8)
return id unless id == INVALID_SPAN_ID
end
end

def generate_span_id_while
id = Random.bytes(8)
id = Random.bytes(8) while id == INVALID_SPAN_ID
id
end

Benchmark.ipsa do |x|
x.report('generate_trace_id') { generate_trace_id }
x.report('generate_trace_id_while') { generate_trace_id_while }
x.compare!
end

Benchmark.ipsa do |x|
x.report('generate_span_id') { generate_span_id }
x.report('generate_span_id_while') { generate_span_id_while }
x.compare!
end
14 changes: 6 additions & 8 deletions api/lib/opentelemetry/trace.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,21 +26,19 @@ module Trace
#
# @return [String] a valid trace ID.
def generate_trace_id
loop do
id = Random.bytes(16)
return id unless id == INVALID_TRACE_ID
end
id = Random.bytes(16)
id = Random.bytes(16) while id == INVALID_TRACE_ID
id
end

# Generates a valid span identifier, an 8-byte string with at least one
# non-zero byte.
#
# @return [String] a valid span ID.
def generate_span_id
loop do
id = Random.bytes(8)
return id unless id == INVALID_SPAN_ID
end
id = Random.bytes(8)
id = Random.bytes(8) while id == INVALID_SPAN_ID
id
end

# Returns the current span from the current or provided context
Expand Down