Time difference in C++

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>.

Leave a Comment