I am working on a two-dimensional game engine that has a LimitFrameRate function to ensure that the game does not start so fast that the user cannot play the game. In this game engine, game speed is tied to frame rate. Therefore, it is usually required to limit the frame rate to about 60 frames per second. The code of this function is relatively simple: calculate the amount of time left before we start working on the next frame, convert it to milliseconds, fill it up with the number of milliseconds (this can be 0), repeat until it is exactly at the right time, then exit. Here is the code:
public virtual void LimitFrameRate(int fps)
{
long freq;
long frame;
freq = System.Diagnostics.Stopwatch.Frequency;
frame = System.Diagnostics.Stopwatch.GetTimestamp();
while ((frame - previousFrame) * fps < freq)
{
int sleepTime = (int)((previousFrame * fps + freq - frame * fps) * 1000 / (freq * fps));
System.Threading.Thread.Sleep(sleepTime);
frame = System.Diagnostics.Stopwatch.GetTimestamp();
}
previousFrame = frame;
}
, , - , . 15 , . , . . , , CPU.
:
? ( , ), . () 7 , 7 ( , ), , . :