save
This commit is contained in:
68
CanCommon/Statistics.cs
Normal file
68
CanCommon/Statistics.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
|
||||
namespace CanCommon;
|
||||
|
||||
/// <summary>
|
||||
/// Thread-safe counters + timing shared by master and slave.
|
||||
/// The hot path uses <see cref="Interlocked"/> so a reporting thread can take
|
||||
/// consistent snapshots without locking the sender/receiver loop.
|
||||
/// </summary>
|
||||
public sealed class Statistics
|
||||
{
|
||||
private long _frames;
|
||||
private long _payloadBytes;
|
||||
private long _errors; // TX errors (master) or CAN/bus error frames (slave)
|
||||
private long _validFrames; // slave only
|
||||
private long _invalidFrames; // slave only
|
||||
|
||||
private readonly Stopwatch _sw = new();
|
||||
|
||||
public void Start() => _sw.Restart();
|
||||
public void Stop() => _sw.Stop();
|
||||
public double ElapsedSeconds => _sw.Elapsed.TotalSeconds;
|
||||
|
||||
public void AddFrame(int payloadBytes)
|
||||
{
|
||||
Interlocked.Increment(ref _frames);
|
||||
Interlocked.Add(ref _payloadBytes, payloadBytes);
|
||||
}
|
||||
|
||||
/// <summary>Bulk variant for batched transmit (one sendmmsg accepting <paramref name="count"/> frames).</summary>
|
||||
public void AddFrames(int count, int payloadBytes)
|
||||
{
|
||||
Interlocked.Add(ref _frames, count);
|
||||
Interlocked.Add(ref _payloadBytes, (long)count * payloadBytes);
|
||||
}
|
||||
|
||||
public void AddValid(int payloadBytes)
|
||||
{
|
||||
Interlocked.Increment(ref _frames);
|
||||
Interlocked.Increment(ref _validFrames);
|
||||
Interlocked.Add(ref _payloadBytes, payloadBytes);
|
||||
}
|
||||
|
||||
public void AddInvalid()
|
||||
{
|
||||
Interlocked.Increment(ref _frames);
|
||||
Interlocked.Increment(ref _invalidFrames);
|
||||
}
|
||||
|
||||
public void AddError() => Interlocked.Increment(ref _errors);
|
||||
|
||||
public Snapshot Take() => new(
|
||||
Volatile.Read(ref _frames),
|
||||
Volatile.Read(ref _payloadBytes),
|
||||
Volatile.Read(ref _validFrames),
|
||||
Volatile.Read(ref _invalidFrames),
|
||||
Volatile.Read(ref _errors),
|
||||
_sw.Elapsed.TotalSeconds);
|
||||
|
||||
public readonly record struct Snapshot(
|
||||
long Frames, long PayloadBytes, long ValidFrames, long InvalidFrames, long Errors, double Seconds)
|
||||
{
|
||||
public double FramesPerSecond => Seconds > 0 ? Frames / Seconds : 0;
|
||||
public double PayloadBytesPerSecond => Seconds > 0 ? PayloadBytes / Seconds : 0;
|
||||
public double PayloadMbps => PayloadBytesPerSecond * 8.0 / 1_000_000.0;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user