I've tried to write a simple timer class that could later be used in games, such as for updating the screen every second. Problem is, I read gettimeofday()
was UNIX-specific and unsafe to use as well (that last one I'm not sure about). I know C has a clock()
function, but it only has second precision.
Is there a way to get time in a cross-platform way that has millisecond precision at the very least? I know Boost and other libraries exist, but I prefer not to use them for various reasons.
class Timer
{
private:
bool m_isRunning;
int m_startTime;
int m_delayAmount;
double m_initialDelay;
public:
Timer(int delayAmount, double initialDelay = 0.0)
{
m_delayAmount = delayAmount * 1000;
m_initialDelay = initialDelay/1000;
}
void start()
{
m_startTime = getMilliseconds();
clock_t endwait = clock() + m_initialDelay * CLOCKS_PER_SEC;
while (clock() < endwait);
m_isRunning = true;
}
void stop()
{
m_isRunning = false;
}
bool isRunning()
{
return m_isRunning;
}
bool hasTicked()
{
if (getMilliseconds() - m_startTime > m_delayAmount)
{
m_startTime = getMilliseconds();
return true;
}
else
{
return false;
}
}
int getMilliseconds() const
{
timeval t;
gettimeofday(&t, NULL);
return (t.tv_sec * 1000000) + t.tv_usec;
}
};
This is kinda how you would use it. The program just prints a message every second after an initial delay of 3 seconds.
int main (int argc, char * const argv[])
{
Timer timer(1000, 3000);
timer.start();
int i = 1;
while (timer.isRunning())
{
if (timer.hasTicked())
{
cout << "tick " << i++ << endl;
}
}
}
while (clock() < endwait);
. It will basically burn your CPU out as it goes to 100% utilization in a tight loop. Your timer may work for this scenario but overall not that useful. I would expect it to take an initial delay, a recurring delay andfunction
. Then the function is automatically called each time the time out period is reached. Here you have to actually check to see to see if the timer has gone off. \$\endgroup\$