Microtime() Equivalent for C and C++?

There is no exact equivalent to PHP's microtime(), but you could a function with a similar functionality based on the following code:

Mac OS X and probably also Linux/Unix

#include <sys/time.h>
struct timeval time;
gettimeofday(&time, NULL); #This actually returns a struct that has microsecond precision.
long microsec = ((unsigned long long)time.tv_sec * 1000000) + time.tv_usec;

(based on: http://brian.pontarelli.com/2009/01/05/getting-the-current-system-time-in-milliseconds-with-c/)


Windows:

unsigned __int64 freq;
QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
double timerFrequency = (1.0/freq);

unsigned __int64 startTime;
QueryPerformanceCounter((LARGE_INTEGER *)&startTime);

//do something...

unsigned __int64 endTime;
QueryPerformanceCounter((LARGE_INTEGER *)&endTime);
double timeDifferenceInMilliseconds = ((endTime-startTime) * timerFrequency);

(answer by Darcara, from: https://stackoverflow.com/a/4568649/330067)


On Linux, you can use gettimeofday, which should give the same information. In fact, I believe that is the function that PHP uses under the covers.


C++11 added some standard timekeeping functions (see section 20.11 "Time utilities") with good accuracy, but most compilers don't support those yet.

Mostly you need to use your OS API, such as gettimeofday for POSIX.

Tags:

C++

C

Microtime