Microtime() Equivalent for C and C++?

user1125551 picture user1125551 · Jul 23, 2012 · Viewed 12.7k times · Source

I am wondering if there is an equivalent to the PHP function microtime() in C and C++. I looked around but couldn't find a definitive answer.

Thanks!

Answer

Lukasz Czerwinski picture Lukasz Czerwinski · Aug 16, 2012

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)