Files
testcan/CanMaster/CanBenchmark.cs
2026-08-20 14:56:23 +07:00

154 lines
7.2 KiB
C#

using CanCommon;
namespace CanMaster;
/// <summary>
/// Orchestrates a master benchmark run: opens the channel, drives <see cref="CanSender"/>
/// on a dedicated thread for the requested duration, prints a 1 Hz live report,
/// and writes a summary + log.
/// </summary>
public sealed class CanBenchmark
{
private readonly BenchmarkOptions _opt;
public CanBenchmark(BenchmarkOptions opt) => _opt = opt;
public int Run()
{
if (_opt.Configure)
InterfaceConfigurator.SetBitrate(_opt.Interface, _opt.Bitrate);
string logPath = RunLogger.BuildPath(_opt.ResultsDir, "master", _opt.Interface, _opt.Bitrate);
using var log = new RunLogger(logPath);
var stats = new Statistics();
byte[] frame = CanFrame.BuildStandard(_opt.CanId, _opt.Dlc, _opt.PayloadFill);
using var channel = new SocketCanChannel(_opt.Interface, rcvTimeoutMs: 0);
channel.Open();
bool extended = CanFrame.IsExtended(frame);
int busBits = CanFrame.BusBitsNominal(_opt.Dlc, extended);
int busBitsWorst = CanFrame.BusBitsWorstCase(_opt.Dlc, extended);
PrintHeader(log, busBits, busBitsWorst);
using var cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) => { e.Cancel = true; cts.Cancel(); };
using var batch = channel.CreateTxBatch(frame, _opt.TxBatch);
var sender = new CanSender(batch, stats, _opt.Dlc, _opt.Realtime, _opt.RtPriority);
stats.Start();
var worker = new Thread(() => sender.Run(cts.Token)) { IsBackground = true, Priority = ThreadPriority.Highest };
worker.Start();
// The worker sets its RT status as soon as it starts; report it once known.
while (sender.RealtimeStatus == "pending") Thread.Sleep(5);
log.Line(sender.RealtimeStatus is null
? $"Realtime : SCHED_FIFO prio {_opt.RtPriority} engaged"
: $"Realtime : not engaged ({sender.RealtimeStatus})");
log.Line("");
RunReportingLoop(log, stats, cts, busBits, busBitsWorst);
cts.Cancel();
worker.Join(2000);
stats.Stop();
PrintSummary(log, stats.Take(), busBits, busBitsWorst);
PrintErrnoBreakdown(log, sender.ErrnoCounts);
log.Line($"\nLog written to: {log.Path}");
return 0;
}
/// <summary>Show which errno the rejected write()s carried — i.e. *why* TX failed.</summary>
private void PrintErrnoBreakdown(RunLogger log, IReadOnlyDictionary<int, long> errnos)
{
if (errnos.Count == 0) return;
log.Line("");
log.Line("TX error breakdown (errno -> count):");
foreach (var (errno, count) in errnos.OrderByDescending(e => e.Value))
log.Line($" {count,10} errno {errno,3} {SocketCanChannel.Strerror(errno)}");
}
private void RunReportingLoop(RunLogger log, Statistics stats, CancellationTokenSource cts, int busBits, int busBitsWorst)
{
var deadline = DateTime.UtcNow.AddSeconds(_opt.DurationSeconds);
long lastFrames = 0, lastErrors = 0;
double lastSec = 0;
int second = 0;
while (DateTime.UtcNow < deadline && !cts.IsCancellationRequested)
{
Thread.Sleep(1000);
var s = stats.Take();
long dFrames = s.Frames - lastFrames;
long dErrors = s.Errors - lastErrors;
double dSec = s.Seconds - lastSec;
double instFps = dSec > 0 ? dFrames / dSec : 0;
double instMbps = dSec > 0 ? dFrames * _opt.Dlc * 8.0 / dSec / 1_000_000.0 : 0;
// Two bus-load figures: nominal (no stuffing) and worst-case stuffing.
// The worst-case one is what `canbusload` prints by default.
double busPct = _opt.Bitrate > 0 ? instFps * busBits / _opt.Bitrate * 100.0 : 0;
double busPctWorst = _opt.Bitrate > 0 ? instFps * busBitsWorst / _opt.Bitrate * 100.0 : 0;
lastFrames = s.Frames; lastErrors = s.Errors; lastSec = s.Seconds;
log.Line($"{DateTime.Now:HH:mm:ss.fff} [{++second,3}s] tx frames={s.Frames,-12} " +
$"inst {instFps,8:0} fps {instMbps,6:0.000} Mbps " +
$"bus {busPct,5:0.0}/{busPctWorst,5:0.0}% " +
$"err={s.Errors} (+{dErrors})");
}
}
private void PrintHeader(RunLogger log, int busBits, int busBitsWorst)
{
log.Line("========== CAN MASTER ==========");
log.Line($"Interface : {_opt.Interface}");
log.Line($"Bitrate : {_opt.BitrateLabel}");
log.Line($"CAN ID : 0x{_opt.CanId:X3}");
log.Line($"DLC : {_opt.Dlc}");
log.Line($"Payload : {_opt.PayloadHex}");
log.Line($"Duration : {_opt.DurationSeconds} s");
log.Line($"Frame on-wire : {busBits} bit (nominal) / {busBitsWorst} bit (worst-case stuffing)");
log.Line($"TX batch : {_opt.TxBatch} frame(s) / sendmmsg");
log.Line($"Started : {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
}
private void PrintSummary(RunLogger log, Statistics.Snapshot s, int busBits, int busBitsWorst)
{
double busPct = _opt.Bitrate > 0 ? s.FramesPerSecond * busBits / _opt.Bitrate * 100.0 : 0;
double busPctWorst = _opt.Bitrate > 0 ? s.FramesPerSecond * busBitsWorst / _opt.Bitrate * 100.0 : 0;
log.Line("");
log.Line("---------- SUMMARY (MASTER) ----------");
log.Line($"CAN bitrate : {_opt.BitrateLabel}");
log.Line($"Duration (actual) : {s.Seconds:0.000} s");
log.Line($"Frames sent : {s.Frames}");
log.Line($"Payload bytes : {s.PayloadBytes}");
log.Line($"Average frame/s : {s.FramesPerSecond:0.00}");
log.Line($"Payload throughput : {s.PayloadBytesPerSecond:0} B/s ({s.PayloadMbps:0.0000} Mbps)");
log.Line($"Bus load : {busPct:0.0} % (nominal) / {busPctWorst:0.0} % (worst-case stuffing)");
// Same columns canbusload prints: <if>@<bitrate> <frames/s> <total bit/s> <payload bit/s> <pct>%
// (worst-case stuffing, matching `canbusload` default) so the two can be compared 1:1.
double totalBps = s.FramesPerSecond * busBitsWorst;
double payloadBps = s.FramesPerSecond * _opt.Dlc * 8.0;
log.Line($"canbusload-style : {_opt.Interface}@{_opt.Bitrate} {s.FramesPerSecond,7:0} {totalBps,9:0} {payloadBps,9:0} {busPctWorst,3:0}%");
log.Line($"TX errors : {s.Errors}");
log.Summary(new Dictionary<string, string>
{
["role"] = "master",
["interface"] = _opt.Interface,
["bitrate"] = _opt.Bitrate.ToString(),
["duration_s"] = s.Seconds.ToString("0.000"),
["frames_sent"] = s.Frames.ToString(),
["payload_bytes"] = s.PayloadBytes.ToString(),
["tx_frames_per_s"] = s.FramesPerSecond.ToString("0.00"),
["payload_mbps"] = s.PayloadMbps.ToString("0.0000"),
["bus_bits_per_frame"] = busBits.ToString(),
["bus_load_pct"] = busPct.ToString("0.00"),
["bus_load_pct_worstcase"] = busPctWorst.ToString("0.00"),
["tx_batch"] = _opt.TxBatch.ToString(),
["tx_errors"] = s.Errors.ToString(),
});
}
}