Timer class for games 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() &lt; endwait);
      m_isRunning = true;
   }

   void stop()
   {
      m_isRunning = false;
   }

   bool isRunning()
   {
      return m_isRunning;
   }

   bool hasTicked()
   {
      if (getMilliseconds() - m_startTime &gt; m_delayAmount)
      {
         m_startTime = getMilliseconds();
         return true;
      }
      else
      {
         return false;
      }

   }

   int getMilliseconds() const
   {
      timeval t;
      gettimeofday(&amp;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 &lt;&lt; "tick " &lt;&lt; i++ &lt;&lt; endl;
      }
   }
}
I think you should take a look at std::chrono and std::thread.

If you want to replicate, say, a VB timer or whatever (something that calls a function every second), you can do this:

template&lt;typename Func&gt;
void timer(Func func, unsigned interval)
{
    while(true)
    {
        std::this_thread

        std::this_thread::sleep_for(;
            std::chrono::milliseconds(interval));   
        func();
    }
}


Of course, you can change that into a functor and give it a bool for start and stop.

if you just want to measure the elapsed time then just use chrono

std::chrono::system_clock::time_point start=std::chrono::system_clock::now();    
//start timer 
//do stuff
std::chrono::duration&lt;double&gt; time_taken=std::chrono::system_clock::now() - start;


Don't reinvent the wheel.  If you don't have access to C++11, then all of this functionality can be used from Boost.