Reputation: 159
MISRA and AUTOSAR do not allow us to use the time()
function of <ctime>
(and <time.h>
).
Rule 18-0-4: The time handling functions of library
<ctime>
shall not be used.
Is there an alternative to the time()
function in C++?
There is the time library <chrono>
. But there I didn't find a function that returns the current time like time()
. Or am I missing something?
Upvotes: 3
Views: 1014
Reputation: 648
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.Upvotes: 3