Limiting framerate for use of PeekMessage()

Hey, I'm using PeekMessage in my windows loop but if unmanaged I'm told it can cause an awful lot of stress on the processor so I want to limit it with a simple FPS limit.

1
2
3
4
5
6
7
8
9
10
11
12
MSG msg;
while(true){
    while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) > 0){
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    if(msg.message == WM_QUIT)
        break;
    render_frame();
    limit_frames(FRAMELIMIT); //Macro defined globally
}
return msg.wParam;


1
2
3
4
5
6
7
8
void limit_frames(int fps){
	static clock_t time = 0;
	clock_t frameLimit = (1.0f/(float)fps);
	clock_t frame = (clock() - time) / CLOCKS_PER_SEC;
	if(frameLimit - frame > 0)
		Sleep((frameLimit - frame) * 1000.0);
	time = clock();
}


My problem is that the frame limit does not work unless FRAMELIMIT is defined as 1, no other number will work... Why?
Well, if FRAMELIMIT is 2, what happens when you feed it to limit_frames?

It is used in: frameLimit = (1.0f/(float)fps);

So frameLimit = 1.0 / 2.0 = .5 converted to an integral type (which frameLimit is) = 0.

So, for any number greater than 1.0, frameLimit will be set to 0.
I suggest using chrono:

1
2
3
4
5
6
7
8
9
10
11
12
void Fps::limit()
{
    t2 = std::chrono::high_resolution_clock::now();
    delay = std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count();

    // We now know the delay, let's check it against our sleep time:
    if (delay < min_time)
		std::this_thread::sleep_for(std::chrono::nanoseconds(static_cast<int>(min_time - delay)));

    // Reset the starting timer.
    t1 = std::chrono::high_resolution_clock::now();
}


where min_time = 1E9f / fps;

Make this part of a class and you have a simple frame limiter.
Well I'm not.quite sure if I like the looks of that, I think.I'll just change the initiation to a double... Should fix my problem right?

(although this may not be the best method of frame limiting, u am only using it for learning purposes, ie just use that while I learn about other stuff for now)
Topic archived. No new replies allowed.