Page 1 of 1
Timing (C++)
Posted: Fri Aug 24, 2007 12:19 pm
by Zacariaz
Just for fun, ive made the letter X move around in the console at random, it was to test wether my assumption that the timing would be a problem was indeed a problem, and yes...
Im using a:
while(true) {
...
}
loop, and i works fine but way to fast. I saw somewhere a guide to how to alter the timing so that it would, well, work slower, but i cant seem to find it again, anyone?
Re: Timing (C++)
Posted: Fri Aug 24, 2007 1:36 pm
by Solar
Zacariaz wrote:I saw somewhere a guide to how to alter the timing so that it would, well, work slower, but i cant seem to find it again, anyone?
Same answer as for the other question: Standard C++ doesn't offer this, you have to look into the APIs provided by the OS or third party libraries.
If anyone wants to talk him through it, last time I looked he was programming on Windows.
Posted: Fri Aug 24, 2007 2:14 pm
by Zacariaz
ok, never mind then...
Posted: Fri Aug 24, 2007 6:45 pm
by pcmattman
Try this to limit the number of times per second a loop can execute [Windows]:
Code: Select all
// limits the FPS
void LimitFPS( int max_fps )
{
// from http://www.geisswerks.com/ryan/FAQS/timing.html
// timer must be at a resolution of 1ms at the start of this code
// the time since the last frame
static LARGE_INTEGER m_prev_end_of_frame = {0};
// the timer frequency and counter
LARGE_INTEGER m_high_perf_timer_freq,t;
// get the frequency
if( !QueryPerformanceFrequency( &m_high_perf_timer_freq ) )
m_high_perf_timer_freq.QuadPart = 0;
// get the counter
QueryPerformanceCounter(&t);
// make sure the frame has been initialized
if (m_prev_end_of_frame.QuadPart != 0)
{
// how many ticks do we need to wait for?
int ticks_to_wait = (int)m_high_perf_timer_freq.QuadPart / max_fps;
// done yet
int done = 0;
// main wait loop
do
{
// get the time
QueryPerformanceCounter(&t);
// how many ticks have passed?
int ticks_passed = (int)((__int64)t.QuadPart - (__int64)m_prev_end_of_frame.QuadPart);
// how many ticks left?
int ticks_left = ticks_to_wait - ticks_passed;
// check if time has wrapped
if (t.QuadPart < m_prev_end_of_frame.QuadPart) // time wrap
done = 1;
// same as above
if (ticks_passed >= ticks_to_wait)
done = 1;
// if not done, give up the timeslice
if (!done)
{
// > 0.002 seconds left, sleep for some time
// saves CPU time and hence laptop battery power
if (ticks_left > (int)m_high_perf_timer_freq.QuadPart*2/1000)
Sleep(1);
else
for ( int i=0; i < 10; i++ )
Sleep(0);
}
}
while (!done);
}
// either way, the end of the frame has to be NOW
m_prev_end_of_frame = t;
}
Posted: Fri Aug 24, 2007 8:48 pm
by Zacariaz
thanks