Getting the current system time in milliseconds with C++

After doing quite a bit of C++ recently, I thought I would post my method for getting the current system time in milliseconds in C++ for both Mac OS X and Windows. The Mac version might translate to other Unix platforms, but you’ll have to check the docs or man pages.

Mac OS X

#include <sys/time.h>
timeval time;
gettimeofday(&time, NULL);
long millis = (time.tv_sec * 1000) + (time.tv_usec / 1000);

This actually returns a struct that has microsecond precision.


#include "windows.h"
WORD millis = (time.wSeconds * 1000) + time.wMilliseconds;

This code gives the milliseconds within the last minute. If you want milliseconds since epoch or some other fixed point in time it will require a bit more math on the SYSTEMTIME struct.