Is Microtime () equivalent for C and C ++?

I am wondering if there is an equivalent of PHP microtime () function in C and C ++. I looked around, but could not find a definitive answer.

Thanks!

+8
source share
6 answers

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

+6
source

There is no exact equivalent of PHP microtime (), but you can use a function with similar functionality based on the following code:

Mac OS X and possibly 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/ )


Window:

 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); 

(Darcara's answer, from: https://stackoverflow.com/a/167189/ )

+8
source

C ++ 11 added some standard timing functions (see section 20.11 “Time Utilities”) with good accuracy, but most compilers do not yet support them.

Basically you should use your OS API, for example gettimeofday for POSIX.

+4
source

For temporary sections of code, try std :: clock , which returns ticks, and then divide by CLOCKS_PER_SEC .

+2
source

libUTP (the UTorrent Transport Protocol protocol library) has a good example for getting micro-sessions on different platforms.

+1
source

in c ++ 11, I believe the php microtime(true) equivalent is:

 #include <chrono> double microtime(){ return (double(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count()) / double(1000000)); } 
  • but I'm not sure what the C equivalent is, or if there is one at all (as others have already noted, gettimeofday is part of posix, but not part of the c / c ++ specification)

Interestingly, a microsecond is one millionth of a second, but c ++ also supports nanoseconds, which is one billionth of a second, I think you will get higher precision with std::chrono::nanoseconds instead of std::chrono::microseconds , but this the moment you are likely to encounter a maximum number limit equal to double , and the function name will be misleading (such a function should have the name nanotime() not microtime() , and the return value should probably be more than double), by the way I have a collection of php functions ported to c ++ here: https://github.com/di vinity76 / phpcpp (and among them microtime ())

0
source

All Articles