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!
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!
in c++11 i believe the equivalent to php's
microtime(true)
is:interestingly a microsecond is one millionth of a second, but c++ also supports nanoseconds, which is one BILLIONTH of a second, i guess you'd get higher precision with
std::chrono::nanoseconds
instead ofstd::chrono::microseconds
, but at that point you'd probably run into max number limits ofdouble
, and the function name would be misleading (such a function should have the namenanotime()
notmicrotime()
, and the return should probably be something bigger than double), btw i have a collection of php-functions-ported-to-c++ here: https://github.com/divinity76/phpcpp (and microtime() is among them)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.
For timing sections of code, try std::clock, which returns ticks, then divide by
CLOCKS_PER_SEC
.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
(based on: http://brian.pontarelli.com/2009/01/05/getting-the-current-system-time-in-milliseconds-with-c/)
Windows:
(answer by Darcara, from: https://stackoverflow.com/a/4568649/330067)
libUTP (uTorrent Transport Protocol library) has a good example on getting the microtime on different platforms.
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.