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?
Using the
<chrono>header requires a little more involvement than the time function.You can create a
time_pointusingstd::chrono::steady_clock::now(). Subtracting twotime_pointinstances creates astd::durationwhich reflects the difference in time between the two instances. You can then use aduration_castto cast this duration to a scale of your choice (microsecond, millisecond etc.) and then use thecountmember function to get the actual time in unsigned type.TL;DR You can measure elapsed time between two events by doing this:
Notes:
time_elapsedis not a floating-point variable,std::chrono::steady_clockshould be preferred tostd::chrono::system_clockbecause the former is a monotonic clock i.e. it will not be adjusted by the OS.