Created
July 27, 2020 03:56
-
-
Save mattleibow/4eb9cd26bcaaaefd5b2f7499d21bf4bd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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