Skip to content

Instantly share code, notes, and snippets.

@mhmd-azeez
Last active March 29, 2023 21:12
Show Gist options
  • Select an option

  • Save mhmd-azeez/3ecee65e34d92ae71b9de60b3f925703 to your computer and use it in GitHub Desktop.

Select an option

Save mhmd-azeez/3ecee65e34d92ae71b9de60b3f925703 to your computer and use it in GitHub Desktop.
A way to artificially throttle FPS useful for video processing applications
using System.Diagnostics;
Console.WriteLine("Hello, World!");
var limiter = new FpsLimiter(60);
var rejected = new List<int>();
var accepted = new List<int>();
var watch = Stopwatch.StartNew();
var count = 0d;
while (true)
{
if (count++ > 50)
{
break;
}
limiter.Wait();
}
Console.WriteLine($"Average FPS: {1000d / (watch.ElapsedMilliseconds / count):N}");
public class FpsLimiter
{
private readonly Stopwatch _stopwatch = new Stopwatch();
private readonly double _frameIntervalMs;
private double _nextFrameTimeMs;
public FpsLimiter(double desiredFps)
{
_frameIntervalMs = 1000.0 / desiredFps;
_nextFrameTimeMs = _stopwatch.Elapsed.TotalMilliseconds + _frameIntervalMs;
_stopwatch.Start();
}
public void Wait()
{
var currentTimeMs = _stopwatch.Elapsed.TotalMilliseconds;
if (_nextFrameTimeMs > currentTimeMs)
{
SpinWait.SpinUntil(() => _stopwatch.ElapsedMilliseconds >= _nextFrameTimeMs);
}
_nextFrameTimeMs += _frameIntervalMs;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment