Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good way to find real time in milliseconds with C++?

I am currently using clock() function supplied by the time.h library. It gives me time precision up to milliseconds. However, it's timing is based on CPU clock cycles. I need a function that instead of using CPU cycles as clock(), will use system realtime with precision up to milliseconds.

I am using linux with gcc compiler.

like image 384
Utku Zihnioglu Avatar asked Dec 06 '10 20:12

Utku Zihnioglu


People also ask

How do you measure time in milliseconds?

To convert an hour measurement to a millisecond measurement, multiply the time by the conversion ratio. The time in milliseconds is equal to the hours multiplied by 3,600,000.

How do you write a millisecond?

The millisecond is a multiple of the second, which is the SI base unit for time. In the metric system, "milli" is the prefix for 10-3. Milliseconds can be abbreviated as ms; for example, 1 millisecond can be written as 1 ms.

Can Time_t store milliseconds?

Use the time() Function to Get Time in Milliseconds in C++ time takes an optional argument of type time_t* , where the returned time value is stored. Alternatively, we can use the function return value to store in the separately declared variable.


2 Answers

#include <sys/time.h>

...

timeval tv;
gettimeofday (&tv, NULL);
return double (tv.tv_sec) + 0.000001 * tv.tv_usec;
like image 135
chrisaycock Avatar answered Nov 15 '22 05:11

chrisaycock


Linux (and POSIX.1-2001) provides gettimeofday() to get current time to microsecond precision.

like image 34
aschepler Avatar answered Nov 15 '22 03:11

aschepler