Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the time difference in microseconds between two timestamps using the Boost library

Tags:

c++

time

boost

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
like image 998
charis Avatar asked Jun 20 '14 10:06

charis


2 Answers

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)

like image 73
sehe Avatar answered Oct 01 '22 00:10

sehe


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';
like image 29
Denis Zaikin Avatar answered Sep 30 '22 23:09

Denis Zaikin