Each time you manually apply conversion factors among units with the <chrono> library, you should ask yourself:
Why do I convert units manually? Isn't that what <chrono> should do for me ?!
The "conversion factor" is 60, or 1000, or 100, or something else. If you see this in your code, you open conversion errors.
Here is the sasha.sochka code rewritten without these conversion factors. And just to understand how common this method is, milliseconds are added for the flash:
#include <chrono> #include <string> #include <sstream> #include <iomanip> #include <iostream> int main() { using namespace std::chrono; steady_clock::time_point start; steady_clock::time_point now = steady_clock::now(); auto d = now -start; auto hhh = duration_cast<hours>(d); d -= hhh; auto mm = duration_cast<minutes>(d); d -= mm; auto ss = duration_cast<seconds>(d); d -= ss; auto ms = duration_cast<milliseconds>(d); std::ostringstream stream; stream << std::setfill('0') << std::setw(3) << hhh.count() << ':' << std::setfill('0') << std::setw(2) << mm.count() << ':' << std::setfill('0') << std::setw(2) << ss.count() << '.' << std::setfill('0') << std::setw(3) << ms.count(); std::string result = stream.str(); std::cout << result << '\n'; }
There are other ways to do this without open conversion factors, so this is just an example. My main point is to avoid conversion factors for hard coding units in your code. They are subject to errors. Even if you get it right when you first encode it, conversion factors are vulnerable to future code maintenance. You can verify your code in the future by requiring that all unit conversions occur in the <chrono> library.
source share