Skip to content

Commit

Permalink
fix: Optimize span and trace ID generation (#1521)
Browse files Browse the repository at this point in the history
  • Loading branch information
fbogsany authored Sep 13, 2023
1 parent a5ed0b4 commit cf8a18b
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 8 deletions.
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

0 comments on commit cf8a18b

Please sign in to comment.