Using the <chrono>
header requires a little more involvement than the time function.
You can create a time_point
using std::chrono::steady_clock::now()
. Subtracting two time_point
instances creates a std::duration
which reflects the difference in time between the two instances. You can then use a duration_cast
to cast this duration to a scale of your choice (microsecond, millisecond etc.) and then use the count
member function to get the actual time in unsigned type.
TL;DR You can measure elapsed time between two events by doing this:
const auto start = std::chrono::steady_clock::now(); // event 1
// something happens in between...
const auto end = std::chrono::steady_clock::now(); // event 2
const auto time_elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end-start).count();
Notes:
time_elapsed
is not a floating-point variable,
std::chrono::steady_clock
should be preferred to std::chrono::system_clock
because the former is a monotonic clock i.e. it will not be adjusted by the OS.