I recently got asked how to measure time in C++ in milliseconds. Surprise, surprise: It’s very easy:

#include <ctime>
#include <iostream>

using namespace std;

[ ... ]

inline clock_t getMilliSecs() { 
    return clock() / (CLOCKS_PER_SEC / 1000); 
}

[ ... ]

clock_t start = getMilliSecs();
// do stuff
cout << "Elapsed time: " << (getMilliSecs() - start) << "ms" << endl;

This seems to work well at first sight, but clock() measures cpu time not the real time. The following snippet will run for 5 seconds, but the measured elapsed time is something like 0ms:

clock_t start = getMilliSecs();
sleep(5)
cout << "Elapsed time: " << (getMilliSecs() - start) << "ms" << endl;

Another way to measure the time is to use gettimeofday. The following example will print out the real time:

#include <sys/time.h>
#include <iostream>

using namespace std;

[ ... ]

inline long getMilliSecs() { 
    timeval t;    
    gettimeofday(&t, NULL);
    return t.tv_usec;
}

[ ... ]

long start = getMilliSecs();
sleep(5);
cout << "Elapsed time: " << (getMilliSecs() - start) << "ms" << endl;

Of course, it depends on your requirement which variant is better suited for your special case.

  1. James (2011-01-22 06:53)

    Just to let you know, you need a little more logic to run a game clock.clock() is returning the processor time which is great until your program switches cores and the processor clock is radically different.Then your start time from the previous loop/iteration is really far behind or really far ahead.You can still run on the ‘gettimeofday,’ but if the user lives in a country that has daylight savings time, or if their clock is automatically updated and changed (sync’d to a time server) then you’ll run into the same problems.Keep a clock variable for the milliseconds that the game is running. When computing the time delta, check for less than zero or really large values. If the delta is clean, add it to your game clock.

  2. joe (2011-01-22 07:05)

    Thank you for your comment. You’re absolutely right. To be honest, I never thought about the problems you pointed to with ‘gettimeofday’. The solution you came up with sounds very good to me.

  3. James (2011-01-22 11:19)

    Lol, only because I ran into a bug where my game would lock up on Macs. Another solution is to set the Thread affinity of your program so that it won’t switch cores…

  4. Florent (2011-12-30 15:48)

    I think your code is wrong.

    This is how you should convert it:

    inline long getMilliSecs() {
    timeval t;
    gettimeofday(&t, NULL);
    return t.tv_sec*1000 + t.tv_usec/1000;
    }

Add your comment now