34
votes

How can I get (using the std::chrono library) the difference between two points in time in milliseconds?

I could do that using this:

std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();

std::chrono::time_point<std::chrono::system_clock> foo = now + std::chrono::milliseconds(100);

std::chrono::duration<float> difference = foo - now;

const int milliseconds = difference.count() * 1000;

How can I get this time in milliseconds, so I can use the duration as a unsigned int, and not a float and then multiply by 1000?

4
chrono::duration_cast<chrono::milliseconds>(end_time - start_time).count()zoska
it took me 2 seconds. google brought me here to your answer.manit
To whoever comes here after googling for a way to get a time difference in milliseconds: careful! This question, and the answers, focus on how to get a duration as an integer amount of milliseconds. If you have time points with a higher precision (e.g. nanoseconds) and you want to preserve all digits without truncating, but you want to convert to milliseconds, you can use duration_cast<duration<float,std::milli>(difference).count(). Using duration_cast<milliseconds>(duration).count() will truncate your digits since milliseconds is basically a duration<long,milli>.Michele Piccolini

4 Answers

50
votes

std::chrono::duration has two template parameters, the second being exactly the unit of measure. You can invoke std::chrono::duration_cast to cast from one duration type to another. Also, there is a predefined duration type for milliseconds: std::chrono::milliseconds. Composing this together:

auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(foo - now);

To get the actual number of milliseconds, use duration::count:

auto ms = milliseconds.count();

Its return type is duration::rep, which for standard duration types like std::chrono::milliseconds is a signed integer of unspecified size.

9
votes
chrono::duration_cast<chrono::milliseconds>(end_time - start_time).count()
4
votes

I had issues with the duration printing out with letters like e-09. Here's how I fixed it:

auto start = std::chrono::high_resolution_clock::now();
< run your function or code here >
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> elapsed = finish - start;
std::cout << "Elapsed Time: " << elapsed.count() << " seconds" << std::endl;

And now I get desired results:

Elapsed Time: 34.406 seconds
1
votes

http://www.cplusplus.com/reference/chrono/duration_cast/

std::chrono::duration_cast<std::chrono::milliseconds>();