Does anyone know how to calculate time difference in C++ in milliseconds?
I used difftime
but it doesn't have enough precision for what I'm trying to measure.
The difftime() function returns the number of seconds elapsed between time time1 and time time0, represented as a double. Each of the times is specified in calendar time, which means its value is a measurement (in seconds) relative to the Epoch, 1970-01-01 00:00:00 +0000 (UTC).
The time_t datatype is a data type in the ISO C library defined for storing system time values. Such values are returned from the standard time() library function. This type is a typedef defined in the standard <time.
To get the elapsed time, we can get the time using clock() at the beginning, and at the end of the tasks, then subtract the values to get the differences. After that, we will divide the difference by CLOCK_PER_SEC (Number of clock ticks per second) to get the processor time.
We can use the clock() function provided by the <time. h> header file to calculate the CPU time consumed by a task within a C application. It returns the clock_t type, which stores the total number of clock ticks.
I know this is an old question, but there's an updated answer for C++0x. There is a new header called <chrono>
which contains modern time utilities. Example use:
#include <iostream> #include <thread> #include <chrono> int main() { typedef std::chrono::high_resolution_clock Clock; typedef std::chrono::milliseconds milliseconds; Clock::time_point t0 = Clock::now(); std::this_thread::sleep_for(milliseconds(50)); Clock::time_point t1 = Clock::now(); milliseconds ms = std::chrono::duration_cast<milliseconds>(t1 - t0); std::cout << ms.count() << "ms\n"; } 50ms
More information can be found here:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2661.htm
There is also now a boost implementation of <chrono>
.
You have to use one of the more specific time structures, either timeval (microsecond-resolution) or timespec (nanosecond-resolution), but you can do it manually fairly easily:
#include <time.h>
int diff_ms(timeval t1, timeval t2)
{
return (((t1.tv_sec - t2.tv_sec) * 1000000) +
(t1.tv_usec - t2.tv_usec))/1000;
}
This obviously has some problems with integer overflow if the difference in times is really large (or if you have 16-bit ints), but that's probably not a common case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With