// // Copyright (c) StellaOps. Licensed under BUSL-1.1. // using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Engines; using System.Text.Json; namespace StellaOps.HybridLogicalClock.Benchmarks; /// /// Benchmarks for HlcTimestamp operations. /// Measures parsing, serialization, and comparison performance. /// [MemoryDiagnoser] [SimpleJob(RunStrategy.Throughput, iterationCount: 10)] public class HlcTimestampBenchmarks { private HlcTimestamp _timestamp; private string _sortableString = null!; private string _jsonString = null!; private HlcTimestamp[] _timestamps = null!; private static readonly JsonSerializerOptions JsonOptions = new(); [GlobalSetup] public void Setup() { _timestamp = new HlcTimestamp { PhysicalTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), NodeId = "scheduler-east-1", LogicalCounter = 42 }; _sortableString = _timestamp.ToSortableString(); _jsonString = JsonSerializer.Serialize(_timestamp, JsonOptions); // Generate array of timestamps for sorting benchmark _timestamps = new HlcTimestamp[1000]; var random = new Random(42); for (int i = 0; i < _timestamps.Length; i++) { _timestamps[i] = new HlcTimestamp { PhysicalTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + random.Next(-1000, 1000), NodeId = $"node-{random.Next(1, 10)}", LogicalCounter = random.Next(0, 1000) }; } } /// /// Benchmark ToSortableString serialization. /// [Benchmark] public string ToSortableString() { return _timestamp.ToSortableString(); } /// /// Benchmark Parse from sortable string. /// [Benchmark] public HlcTimestamp Parse() { return HlcTimestamp.Parse(_sortableString); } /// /// Benchmark TryParse from sortable string. /// [Benchmark] public bool TryParse() { return HlcTimestamp.TryParse(_sortableString, out _); } /// /// Benchmark full round-trip: serialize then parse. /// [Benchmark] public HlcTimestamp RoundTrip() { var str = _timestamp.ToSortableString(); return HlcTimestamp.Parse(str); } /// /// Benchmark JSON serialization. /// [Benchmark] public string JsonSerialize() { return JsonSerializer.Serialize(_timestamp, JsonOptions); } /// /// Benchmark JSON deserialization. /// [Benchmark] public HlcTimestamp JsonDeserialize() { return JsonSerializer.Deserialize(_jsonString, JsonOptions); } /// /// Benchmark CompareTo operation. /// [Benchmark] public int CompareTo() { var other = new HlcTimestamp { PhysicalTime = _timestamp.PhysicalTime + 1, NodeId = _timestamp.NodeId, LogicalCounter = 0 }; return _timestamp.CompareTo(other); } /// /// Benchmark sorting 1000 timestamps. /// [Benchmark] public void Sort1000Timestamps() { var copy = (HlcTimestamp[])_timestamps.Clone(); Array.Sort(copy); } }