Last active
March 29, 2023 21:12
-
-
Save mhmd-azeez/3ecee65e34d92ae71b9de60b3f925703 to your computer and use it in GitHub Desktop.
A way to artificially throttle FPS useful for video processing applications
This file contains hidden or 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
| 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