Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
C# Calculate Items or Bytes Per Second
public class CalculateItemsPerSecond
{
private readonly int _limit;
private bool _running;
private readonly Stopwatch _timer;
private LimitedList<double> rvlst;
public CalculateItemsPerSecond(int limit = 10)
{
_timer = new Stopwatch();
_limit = limit;
_running = false;
rvlst = new LimitedList<double>(_limit);
}
public void Start()
{
rvlst = new LimitedList<double>(_limit);
_timer.Restart();
_running = true;
}
public void Stop()
{
_timer.Stop();
_running = false;
}
public double ItemsPerSecond(int itemsProcessed)
{
return ItemsPerSecond((double) itemsProcessed);
}
public double ItemsPerSecond(long itemsProcessed)
{
return ItemsPerSecond((double) itemsProcessed);
}
public double ItemsPerSecond(float itemsProcessed)
{
return ItemsPerSecond((double)itemsProcessed);
}
public double ItemsPerSecond(double itemsProcessed)
{
if ((int) itemsProcessed == 0)
return 0;
if (!_running)
Start();
rvlst.Add(itemsProcessed / _timer.Elapsed.TotalSeconds);
var rv = rvlst.AverageEx();
if (rv < 1)
return 0;
return rv;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment