Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
RuntimeProfiler.cs
1using System.Collections.ObjectModel;
2using System.Diagnostics;
3
5
10public sealed class RuntimeProfiler : IDisposable
11{
12 private readonly object _sync = new();
13 private readonly Func<double> _clock;
14 private readonly Dictionary<long, TelemetrySource> _sources = [];
15 private Queue<TelemetrySnapshot> _history = new(120);
16 private TelemetrySnapshot? _latestSnapshot;
17 private TelemetryOptions _options = new();
18 private long _nextId, _generation;
19 private int _requests;
20 private bool _disposed, _truncated;
21 private double _started;
22
24 public RuntimeProfiler() : this(() => Stopwatch.GetTimestamp() / (double)Stopwatch.Frequency) { }
25
28 internal RuntimeProfiler(Func<double> clock) => _clock = clock;
29
31 public bool IsCollecting => Volatile.Read(ref _requests) != 0;
32
35 {
36 get
37 {
38 lock (_sync)
39 return _options;
40 }
41 }
42
45 public void Configure(TelemetryOptions options)
46 {
47 ArgumentNullException.ThrowIfNull(options);
48 options.Validate();
49
50 lock (_sync)
51 {
52 ObjectDisposedException.ThrowIf(_disposed, this);
53
54 if (_requests != 0)
55 throw new InvalidOperationException("Configure telemetry while inactive.");
56
57 if (_sources.Count > options.SourceCapacity ||
58 _sources.Values.Any(s => s.Metrics.Count > options.MetricCapacity))
59 throw new InvalidOperationException("Configured limits are smaller than registered detail.");
60
61 _options = options;
62 _history = new Queue<TelemetrySnapshot>(options.HistoryCapacity);
63 ResetCore();
64 }
65 }
66
69 public IDisposable Start()
70 {
71 lock (_sync)
72 {
73 ObjectDisposedException.ThrowIf(_disposed, this);
74
75 if (_requests == 0)
76 {
77 _generation++;
78 _started = _clock();
79 ClearAccumulators();
80
81 foreach (var source in _sources.Values)
82 foreach (var accumulator in source.Metrics.Values)
83 accumulator.Rebase();
84 }
85
86 _requests++;
87 return new Request(this);
88 }
89 }
90
95 public TelemetrySource? RegisterSource(string name, string backend)
96 {
97 ValidateName(name);
98 ValidateName(backend);
99
100 lock (_sync)
101 {
102 ObjectDisposedException.ThrowIf(_disposed, this);
103
104 if (_sources.Count >= _options.SourceCapacity)
105 {
106 _truncated = true;
107 return null;
108 }
109
110 var source = new TelemetrySource(
111 this,
112 ++_nextId,
113 name,
114 backend);
115
116 _sources.Add(source.Id, source);
117 return source;
118 }
119 }
120
125 internal TelemetrySource? TryRegisterSource(string name, string backend)
126 {
127 lock (_sync)
128 return _disposed ? null : RegisterSource(name, backend);
129 }
130
134 {
135 lock (_sync)
136 {
137 Advance();
138 return _latestSnapshot;
139 }
140 }
141
144 public IReadOnlyList<TelemetrySnapshot> GetHistory()
145 {
146 lock (_sync)
147 {
148 Advance();
149 return Array.AsReadOnly(_history.ToArray());
150 }
151 }
152
154 public void Reset()
155 {
156 lock (_sync)
157 {
158 ObjectDisposedException.ThrowIf(_disposed, this);
159 ResetCore();
160 }
161 }
162
164 public void Dispose()
165 {
166 lock (_sync)
167 {
168 if (_disposed)
169 return;
170
171 _disposed = true;
172 _requests = 0;
173 _generation++;
174 _sources.Clear();
175 _history.Clear();
176 _latestSnapshot = null;
177 }
178 }
179
182 internal long Begin() => IsCollecting ? Volatile.Read(ref _generation) : 0;
183
190 internal bool Define(
191 TelemetrySource source,
192 string name,
193 TelemetryAvailability availability,
195 {
196 ValidateName(name);
197
198 lock (_sync)
199 {
200 if (!_sources.ContainsKey(source.Id))
201 return false;
202
203 if (source.Metrics.TryGetValue(name, out var existing))
204 {
205 if (existing.Availability == TelemetryAvailability.Unsupported &&
206 availability == TelemetryAvailability.NotYetSampled)
207 existing.Availability = availability;
208
209 return true;
210 }
211
212 if (source.Metrics.Count >= _options.MetricCapacity)
213 {
214 _truncated = true;
215 return false;
216 }
217
218 source.Metrics.Add(name, new Accumulator { Availability = availability, Kind = kind });
219 return true;
220 }
221 }
222
228 internal void Record(
229 TelemetrySource source,
230 long generation,
231 string metric,
232 double value)
233 {
234 if (generation == 0 || !IsCollecting || !double.IsFinite(value))
235 return;
236
237 lock (_sync)
238 {
239 if (_requests == 0 || generation != _generation || !_sources.ContainsKey(source.Id))
240 return;
241
242 Advance();
243
244 if (!source.Metrics.TryGetValue(metric, out var accumulator))
245 return;
246
247 if (accumulator.Availability is TelemetryAvailability.Unsupported or TelemetryAvailability.NotApplicable)
248 return;
249
250 accumulator.Add(value, _clock());
251 }
252 }
253
256 internal void Retire(TelemetrySource source)
257 {
258 lock (_sync)
259 _sources.Remove(source.Id);
260 }
261
264 internal void MarkTruncated(long generation)
265 {
266 lock (_sync)
267 {
268 if (generation == _generation && _requests != 0)
269 _truncated = true;
270 }
271 }
272
273 private static void ValidateName(string name)
274 {
275 if (string.IsNullOrWhiteSpace(name) || name.Length > 96)
276 throw new ArgumentException("Names must contain 1–96 characters.", nameof(name));
277 }
278
279 private void ResetCore()
280 {
281 _generation++;
282 _history.Clear();
283 _latestSnapshot = null;
284 _started = _clock();
285 ClearAccumulators();
286
287 foreach (var source in _sources.Values)
288 foreach (var accumulator in source.Metrics.Values)
289 accumulator.Rebase();
290 }
291
292 private void ClearAccumulators()
293 {
294 foreach (var source in _sources.Values)
295 foreach (var accumulator in source.Metrics.Values)
296 accumulator.Clear();
297 }
298
299 private void Advance()
300 {
301 if (_requests == 0)
302 return;
303
304 double now = _clock();
305
306 if (now - _started >= _options.Interval.TotalSeconds)
307 Publish(now);
308 }
309
310 private void Publish(double now)
311 {
312 var sources = _sources.Values.Select(source => new TelemetrySourceSnapshot(
313 source.Id,
314 source.Name,
315 source.Backend,
316 new ReadOnlyDictionary<string, TelemetrySummary>(
317 source.Metrics.ToDictionary(p => p.Key, p => p.Value.Snapshot())))).ToArray();
318
319 if (_history.Count == _options.HistoryCapacity)
320 _history.Dequeue();
321
322 _latestSnapshot = new(
323 _generation,
324 _started,
325 now,
326 Array.AsReadOnly(sources),
327 _truncated);
328
329 _history.Enqueue(_latestSnapshot);
330 ClearAccumulators();
331 _started = now;
332 }
333
334 private void Stop()
335 {
336 lock (_sync)
337 {
338 if (_requests == 0)
339 return;
340
341 if (_requests == 1)
342 {
343 double now = _clock();
344
345 if (now > _started)
346 Publish(now);
347
348 _generation++;
349 }
350
351 _requests--;
352 }
353 }
354
355 private sealed class Request(RuntimeProfiler owner) : IDisposable
356 {
357 private RuntimeProfiler? _owner = owner;
358
362 public void Dispose() => Interlocked.Exchange(ref _owner, null)?.Stop();
363 }
364
366 internal sealed class Accumulator
367 {
369 internal TelemetryAvailability Availability;
370
372 internal TelemetryMetricKind Kind;
373
374 private long _count;
375 private double _sum, _min, _max, _last, _observed;
376 private double? _baseline;
377
381 internal void Add(double value, double observed)
382 {
383 _min = _count == 0 ? value : Math.Min(_min, value);
384 _max = _count == 0 ? value : Math.Max(_max, value);
385 _count++;
386 _sum += value;
387 _last = value;
388 _observed = observed;
389 }
390
392 internal void Clear()
393 {
394 if (_count > 0)
395 _baseline = _last;
396
397 _count = 0;
398 _sum = 0;
399 }
400
402 internal void Rebase() => _baseline = null;
403
406 internal TelemetrySummary Snapshot() => new(
407 _count == 0 ? Availability : TelemetryAvailability.Available,
408 _count,
409 _sum,
410 _count == 0 ? null : _min,
411 _count == 0 ? null : _max,
412 _count == 0 ? null : _last)
413 {
414 Kind = Kind,
415 LastObservedSeconds = _count == 0 ? null : _observed,
416 WindowDelta = Kind == TelemetryMetricKind.LifetimeCounter && _count > 0 && _baseline is { } baseline
417 ? _last - baseline
418 : null
419 };
420 }
421}
422
424public sealed class TelemetrySource : IDisposable
425{
426 private readonly RuntimeProfiler _owner;
427
429 internal Dictionary<string, RuntimeProfiler.Accumulator> Metrics { get; } = [];
430
436 internal TelemetrySource(
437 RuntimeProfiler owner,
438 long id,
439 string name,
440 string backend)
441 => (_owner, Id, Name, Backend) = (owner, id, name, backend);
442
444 public long Id { get; }
445
447 public string Name { get; }
448
450 public string Backend { get; }
451
457 public bool Define(
458 string name,
459 TelemetryAvailability availability = TelemetryAvailability.NotYetSampled,
461 => _owner.Define(
462 this,
463 name,
464 availability == TelemetryAvailability.Available ? TelemetryAvailability.NotYetSampled : availability,
465 kind);
466
469 internal void MarkTruncated(long generation) => _owner.MarkTruncated(generation);
470
473 public long BeginSample() => _owner.Begin();
474
479 public void Record(long generation, string metric, double value) => _owner.Record(
480 this,
481 generation,
482 metric,
483 value);
484
486 public void Dispose() => _owner.Retire(this);
487}
Opt-in, bounded runtime measurements independent of legacy CPS notifications.
TelemetrySnapshot? GetLatestSnapshot()
Returns the latest completed bucket, or null before one completes.
bool IsCollecting
Whether any collection request is active; safe on producer threads.
void Dispose()
Stops collection, invalidates in-flight samples, and retires all source handles.
void Reset()
Clears telemetry history and rebases observations without changing renderer counters or leases.
IReadOnlyList< TelemetrySnapshot > GetHistory()
Returns bounded completed buckets in chronological order without consuming them.
TelemetrySource? RegisterSource(string name, string backend)
Registers an explicitly named source without retaining any runtime object.
void Configure(TelemetryOptions options)
Changes shared settings while inactive, clearing previous measurements.
TelemetryOptions Options
Current immutable settings.
IDisposable Start()
Starts or joins collection. Disposing the last request stops collection.
RuntimeProfiler()
Creates an independent collector using the monotonic Stopwatch clock.
Bounded extension source. Define measurements once, capture a generation before work,...
bool Define(string name, TelemetryAvailability availability=TelemetryAvailability.NotYetSampled, TelemetryMetricKind kind=TelemetryMetricKind.Sample)
Defines a measurement before use. Include units and scope in its name.
void Record(long generation, string metric, double value)
Records a finite observation without retaining raw samples.
long BeginSample()
Captures an epoch before measured work; zero means disabled.
void Dispose()
Permanently retires the source; late observations are ignored.
long Id
Session-local identity, unchanged by collector reset or temporary context loss.
record TelemetrySummary(TelemetryAvailability Availability, long Count, double Sum, double? Minimum, double? Maximum, double? Last)
Detached statistics for observations in one window; durations use milliseconds.
record TelemetrySourceSnapshot(long Id, string Name, string Backend, IReadOnlyDictionary< string, TelemetrySummary > Metrics)
Detached source identity, backend label, and measurements. No runtime objects are retained.
TelemetryAvailability
Whether an observation is meaningful for its source and window.
TelemetryMetricKind
How observations should be interpreted when combining windows.
record TelemetryOptions
Validated shared settings; configure only when collection is inactive.
record TelemetrySnapshot(long Generation, double StartedSeconds, double EndedSeconds, IReadOnlyList< TelemetrySourceSnapshot > Sources, bool Truncated)
Detached completed window. Sources can be observed asynchronously within its interval.