UPDATE: code now compiles properly
I would like to calculate the time difference between two timestamps. The resolution is important so it must be in microseconds/milliseconds.
I tried the following but the result is not meaningful:
boost::posix_time::ptime before = (&input[0])->timestamp;
boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();
boost::posix_time::time_period tp (before, now);
std::string str (boost::posix_time::to_simple_string (tp));
cout << str.c_str() << endl;
The result i get is the following:
[2014-Jun-20 12:26:07.711182/2014-Jun-20 12:26:07.711596]
How can i get something like the following instead?
76 μs
You can just use
std::cout << (now - before).total_microseconds() << " µs\n";
std::cout << (now - before).total_milliseconds() << " ms\n";
This does exactly what you want (printing e.g. 76 µs
or 314 ms
)
I recomend to use boost::chrono
boost::chrono::system_clock::time_point before =
boost::chrono::system_clock::now();
//do some work
boost::chrono::system_clock::time_point now =
boost::chrono::system_clock::now();
boost::chrono::nanoseconds t = boost::chrono::duration_cast<boost::chrono::nanoseconds>(now-before);
std::cout << t.count() << "\n";
Why boost chrono? Boost.Chrono vs. Boost.Date_Time
If you need a very simple solution(without boost linking) just use:
inline unsigned long long getCurrentNanos()
{
timespec tv;
clock_gettime(CLOCK_REALTIME, &tv);
return tv.tv_sec*1000000000 + tv.tv_nsec;
}
//...
unsinged long long start = getCurrentNanos();
//do some work
std::cout << getCurrentNanos() - start << '\n';
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