perf: optimize {Trace,Span}_id.is_zero

This commit is contained in:
Simon Cruanes 2025-12-04 12:08:01 -05:00
parent 98cf8fbdbc
commit fe0aa297a6
No known key found for this signature in database
GPG key ID: EBFFF6F283F3A2B4
3 changed files with 22 additions and 4 deletions

View file

@ -11,10 +11,13 @@ let create () : t =
Bytes.set b 0 (Char.unsafe_chr (Char.code (Bytes.get b 0) lor 1)); Bytes.set b 0 (Char.unsafe_chr (Char.code (Bytes.get b 0) lor 1));
b b
(* dark magic, woo. We have an [assert] below to do the bound checks once *)
external unsafe_b_get64 : bytes -> int -> int64 = "%caml_bytes_get64u"
let[@inline] is_zero (self : t) : bool = let[@inline] is_zero (self : t) : bool =
(* try to reduce branches *) (* try to reduce branches *)
assert (Bytes.length self = 8); assert (Bytes.length self = 8);
let n1 = Bytes.get_int64_ne self 0 in let n1 = unsafe_b_get64 self 0 in
n1 = 0L n1 = 0L
let[@inline] is_valid self = not (is_zero self) let[@inline] is_valid self = not (is_zero self)

View file

@ -17,11 +17,14 @@ let[@inline] of_bytes b =
else else
invalid_arg "trace ID must be 16 bytes in length" invalid_arg "trace ID must be 16 bytes in length"
(* dark magic, woo. We have an [assert] below to do the bound checks once *)
external unsafe_b_get64 : bytes -> int -> int64 = "%caml_bytes_get64u"
let[@inline] is_zero (self : t) : bool = let[@inline] is_zero (self : t) : bool =
(* try to reduce branches *) (* try to reduce branches *)
assert (Bytes.length self = 1); assert (Bytes.length self = 16);
let n1 = Bytes.get_int64_ne self 0 in let n1 = unsafe_b_get64 self 0 in
let n2 = Bytes.get_int64_ne self 8 in let n2 = unsafe_b_get64 self 8 in
n1 = 0L && n2 = 0L n1 = 0L && n2 = 0L
let[@inline] is_valid self = not (is_zero self) let[@inline] is_valid self = not (is_zero self)
@ -37,4 +40,12 @@ let[@inline] of_hex_substring s off =
let pp fmt t = Format.fprintf fmt "%s" (to_hex t) let pp fmt t = Format.fprintf fmt "%s" (to_hex t)
let compare = Bytes.compare
module Map = Map.Make (struct
type nonrec t = t
let compare = compare
end)
let k_trace_id : t Hmap.key = Hmap.Key.create () let k_trace_id : t Hmap.key = Hmap.Key.create ()

View file

@ -8,6 +8,8 @@ val create : unit -> t
val dummy : t val dummy : t
val compare : t -> t -> int
val pp : Format.formatter -> t -> unit val pp : Format.formatter -> t -> unit
val is_valid : t -> bool val is_valid : t -> bool
@ -24,6 +26,8 @@ val of_hex : string -> t
val of_hex_substring : string -> int -> t val of_hex_substring : string -> int -> t
module Map : Map.S with type key = t
val k_trace_id : t Hmap.key val k_trace_id : t Hmap.key
(** Hmap key to carry around a {!Trace_id.t}, to remember what the current trace (** Hmap key to carry around a {!Trace_id.t}, to remember what the current trace
is. is.