Keeping program running at constant speed.

This is a discussion on Keeping program running at constant speed. within the C++ Programming forums, part of the General Programming Boards category; Hi guys. I decieded to post here instead of the game board as this problem can relate to any program. ...

Keeping program running at constant speed.

Hi guys. I decieded to post here instead of the game board as this problem can relate to any program. Basically, I have a problem with keeping my game run at a constant speed, and hope the following code with the 2 problems is stated succintly enough.

/* all objects have a speed variable given in pixels per second, frames per second etc.
this code is supposed to make the game run equally fast on all computers since it depends
on the amount of times the logic is called per second. all objects' x-value and y-value are
floating point numbers so they can move a "fractional amount of pixels" whenever the logic is done.

Problem 1: If the logic takes long in the beginning of the game but gets faster and faster (if objects keep getting deleted as the game progresses) the calls_per_second variable will take a while to catch up and the game won't run at a constant speed.

Problem 2: If we update the calls_per_second variable whenever logic_counter increments the calls_per_second is updated 100 times per second making (or some other amount of times per second) the game runs at a constant speed, but if tons of objects get deleted within the 1/100th of a second the game will run extremely fast for the next 1/100th inducing sudden jumps in the game speed. */

Code:

volatile int logic_counter(1); // increments by one 100 times a second (via interrupt - timer function)
main() {
int cycle_counter(1); // counter incrementing by 1 each time logic is performed
while(!key[ESC})
{
cycle_counter++;
int calls_per_second(100*cycle_counter/game_counter);
do_logic(calls_per_second); // moving all objects based on the amount of times the (logic/move) functions are called per second.
if(draw_ready) do_draw(); // rhe draw_ready flag is set 50 times a second via a timer.
}
}

Last edited by Salem; 07-30-2010 at 11:51 PM.
Reason: tagged just the code, so the text wraps

On Windows machines you can use QueryPerformanceCounter() and QueryPerformanceFrequency() to get accurate timing. Note that on dual-core AMDs you will also need to use SetThreadAffinityMask() or risk getting some strange results.