1
\$\begingroup\$

I'm writing a Direct2D game in c++ / WinAPI. I need to render things 60 times every a second using fixed time step.

__int64 time_before = 0;
__int64 time_now;
__int64 frequency;
__int64 time_elapsed;
double frameTime;
if (QueryPerformanceFrequency((LARGE_INTEGER*)&frequency)) {
    frameTime = (double)frequency / 60;
    while (true) {
        //process incoming messages here
        QueryPerformanceCounter((LARGE_INTEGER*)&time_now);
        time_elapsed = time_now - time_before;
        if (time_elapsed >= frameTime) {
            //update and render things here:
            time_start = time_before;
        }
    }
}

Are there any problems, or are there any improvements that can be made?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Can't you use a std::this_thread::sleep_for(std::chrono::milliseconds(x)); or nanosleep()?

Using any of the two sleeps the cpu will be free to do anything else that needs doing meanwhile this process is sleeping. Also this way it can controls doing the rendering at a specific rate and it´s not a good idea to use a while(true) without any sleep because it eats up all the processing time.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Hi there, welcome to Code Review! Would you mind elaborating why the use of those functions would be better than a spin loop? Your answer is a bit lacking in content and authority (it reads like guesswork, rather than "You should do this because reasons like cpu usage or performance or less bugs or ...") \$\endgroup\$
    – Pimgd
    Apr 6, 2016 at 9:48
  • \$\begingroup\$ Thanks, sorry didn´t think of explaining the answer in that way. Using any of the two sleeps the cpu will be free to do anything else that needs doing meanwhile this process is sleeping. Also this way it can controls doing the rendering at a specific rate and it´s not a good idea to use a while(true) without any sleep because it eats up all the processing time. At least that´s what I think, any corrections to the asnwer are welcome :) \$\endgroup\$ Apr 6, 2016 at 13:52
  • \$\begingroup\$ If you put the explanation in the answer, that'd be great \$\endgroup\$
    – Pimgd
    Apr 6, 2016 at 14:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.