C++ Setting Speed of While Loop per Second

Asaaj picture Asaaj · May 18, 2012 · Viewed 10.7k times · Source

I am relatively new to C++, so I don't have a huge amount of experience. I have learned Python, and I am trying to make an improved version of a Python code I wrote in C++. However, I want it to work in real time, so I need to set the speed of a While loop. I'm sure there is an answer, but I couldn't find it. I want a comparable code to this:

rate(timeModifier * (1/dt))

This was the code I used in Python. I can set a variable dt to make calculations more precise, and timeModifier to double or triple the speed (1 sets it to realtime). This means that the program will go through the loop 1/dt times per second. I understand I can include time.h at the header, but I guess I am too new to C++ to understand how to transfer this to my needs.

Answer

slybloty picture slybloty · May 18, 2012

You could write your own timer class:

#include <ctime>

class Timer {
    private:
        unsigned long startTime;
    public:
        void start() {
            startTime = clock();
        }

        unsigned long elapsedTime() {
            return ((unsigned long) clock() - startTime) / CLOCKS_PER_SEC;
        }

        bool isTimeout(unsigned long seconds) {
            return seconds >= elapsedTime();
        }
};


int main() 
{
    unsigned long dt = 10; //in seconds
    Timer t;
    t.start();

    while(true) 
    {
        if(t.elapsedTime() < dt) 
        {
            //do something to pass time as a busy-wait or sleep
        }
        else 
        {
            //do something else
                    t = Timer(); //reset the timer
        }
    }
}

Note that busy-waits are discouraged, since they will hog the CPU. If you don't need to do anything, use the sleep command(Windows) or usleep ( Linux). For more information on making timers in C++, see this link.