FPS limiting?

Started by
3 comments, last by sirob 16 years, 9 months ago
How can I limit the fps of a directx application in C++?
Advertisement
If the time since you rendered last is less than 1 second divided by your frame limit then don't render.


#include <mmsystem.h>void Render(){	static DWORD dwLastFrameTime = 0;	dwFPSLimit = 60; // Or however many frames per second	dwCurrentTime = timeGetTime();	if ((dwCurrentTime - dwLastFrameTime) < (1000 / dwFPSLimit)) // 1000 miliseconds in a second.	{		return;	}	dwLastFrameTime = dwCurrentTime;}

Try the code below by adding them into your render loop.
Please note that timeGetTime() returns time in terms of millisecond if you are using windows xp. The code limits the rendering speed of your loop by 30 milliseconds per frame.


static unsigned long m_dwLastTime;
unsigned long m_dwCurrentTime;

// capture time per frame
m_dwLastTime = m_dwCurrentTime;
m_dwCurrentTime = timeGetTime();

// handle control frame rate
while ( m_dwCurrentTime - m_dwLastTime < 30 )
{
m_dwCurrentTime = timeGetTime();
}
Quote:Original post by CodeReaver
If the time since you rendered last is less than 1 second divided by your frame limit then don't render.


#include <mmsystem.h>void Render(){	static DWORD dwLastFrameTime = 0;	dwFPSLimit = 60; // Or however many frames per second	dwCurrentTime = timeGetTime();	if ((dwCurrentTime - dwLastFrameTime) < (1000 / dwFPSLimit)) // 1000 miliseconds in a second.	{		return;	}	dwLastFrameTime = dwCurrentTime;}


yup, thanks, that helped :)

though theres something odd going on, when I set the fps limit to 60 it works fine (albeit at 64fps) but when I set it to 100 it still works at 64fps. When I change it from 100fps to 200fps it works at 125fps. I can get any fps I want but it isn't working with dwfpslimit directly. Though when set to 120fps it works at 120fps, maybe it's a vsync issue or something... Kinda odd.

[Edited by - chillypacman on July 29, 2007 1:50:18 AM]
You're skipping frames. timeGetTime is an inaccurate timer, so it only returns at a certain frequency. When it does, you immediately assume you've drawn all the frames you needed to by doing:
dwLastFrameTime = dwCurrentTime;
What you should actually be doing is adding one frame's worth of time, and checking again on the next frame. Here's how it should look:
dwLastFrameTime += (1000 / dwFPSLimit);

That might still hit some issues with how it rounds the divide, but it'll be much closer to the FPS you want, especially if you pick numbers that 1000 divides nicely by.

Hope this helps.
Sirob Yes.» - status: Work-O-Rama.

This topic is closed to new replies.

Advertisement