34 lines
1.3 KiB
C#
34 lines
1.3 KiB
C#
using System;
|
||
using System.Threading;
|
||
|
||
namespace FluidSim
|
||
{
|
||
/// <summary>
|
||
/// Tracks the duty cycle of a worker thread using an exponential moving average.
|
||
/// Thread‑safe: one writer (the sim thread), any reader (UI thread).
|
||
/// </summary>
|
||
public class ThreadLoadTracker
|
||
{
|
||
private double _loadPercent; // 0 .. 100, accessed with Volatile.Read/Write
|
||
private const double Alpha = 0.1; // smoothing factor (higher = faster response)
|
||
|
||
/// <summary>
|
||
/// Update the load percentage with a new observation.
|
||
/// </summary>
|
||
/// <param name="busyMs">Time spent on real work in the last cycle.</param>
|
||
/// <param name="totalMs">Total time of the last cycle (work + idle). If zero, ignored.</param>
|
||
public void Record(double busyMs, double totalMs)
|
||
{
|
||
if (totalMs <= 0) return;
|
||
double instantLoad = busyMs / totalMs * 100.0;
|
||
|
||
// Exponential moving average
|
||
double old = Volatile.Read(ref _loadPercent);
|
||
double newLoad = old + Alpha * (instantLoad - old);
|
||
Volatile.Write(ref _loadPercent, newLoad);
|
||
}
|
||
|
||
/// <summary>Current smoothed load percentage (0‑100).</summary>
|
||
public double LoadPercent => Volatile.Read(ref _loadPercent);
|
||
}
|
||
} |