Skip to content

Instantly share code, notes, and snippets.

@mattleibow
Created July 27, 2020 03:56
Show Gist options
  • Save mattleibow/4eb9cd26bcaaaefd5b2f7499d21bf4bd to your computer and use it in GitHub Desktop.
Save mattleibow/4eb9cd26bcaaaefd5b2f7499d21bf4bd to your computer and use it in GitHub Desktop.
public class FrameCounter
{
private readonly int sampleCount;
private int index;
private int sum;
private readonly int[] samples;
private int lastTick;
public FrameCounter(int sampleCount = 100)
{
this.sampleCount = sampleCount;
lastTick = Environment.TickCount;
samples = new int[sampleCount];
}
public float GetCurrentRate()
{
var ticks = System.Environment.TickCount;
var delta = ticks - lastTick;
lastTick = ticks;
return 1000f / CalculateAverage(delta);
}
private float CalculateAverage(int delta)
{
sum -= samples[index];
sum += delta;
samples[index] = delta;
if (++index == sampleCount)
index = 0;
return (float)sum / sampleCount;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment