5

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
charis
  • 429
  • 6
  • 16

2 Answers2

7

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)

sehe
  • 374,641
  • 47
  • 450
  • 633
4

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';
Community
  • 1
  • 1
Denis Zaikin
  • 569
  • 4
  • 10
  • Why is the use of boost::chrono better? – charis Jun 20 '14 at 10:42
  • 1
    Boost chrono most focused on time intervals(as you can see the resolution can be in nanoseconds) and aslo implements (copied from boost doc): "the new time facilities in C++0x, as proposed in N2661 - A Foundation to Sleep On. That document provides background and motivation for key design decisions and is the source of a good deal of information in this documentation". – Denis Zaikin Jun 20 '14 at 11:03