Reputation: 914
I have the following code:
// #includes for <chrono>, <iostream>, etc.
using namespace std;
using namespace chrono;
int main(int argc, char* argv[]) {
auto sysStart = system_clock::now();
LogInit(); // Opens a log file for reading/writing
// Last shutdown time log entry is marked by a preceding null byte
logFile.ignore(numeric_limits<streamsize>::max(), '\0');
if (logFile.fail() || logFile.bad()) {
// Calls GetLastError() and logs the error code and message
LogError("main");
}
// Parse the timestamp at the start of the shutdown log entry
tm end = { 0 };
logFile >> get_time(&end, "[%d-%m-%Y %T");
if (logFile.fail() || logFile.bad()) {
// Same as above. Param is name of function within which error occurred
LogError("main");
}
// Finally, we have the last shutdown time as a chrono::time_point
auto sysEnd = system_clock::from_time_t(mktime(&end));
// Calculate the time for which the system was inactive
auto sysInactive = sysStart - sysEnd;
auto hrs = duration_cast<hours>(sysInactive).count();
auto mins = duration_cast<minutes>(sysInactive).count() - hrs * 60;
auto secs = duration_cast<seconds>(sysInactive).count() - (hrs * 3600) - mins * 60;
auto ms = duration_cast<milliseconds>(sysInactive).count() - (hrs * 3600000)
- (mins * 60000) - secs * 1000;
return 0;
}
It works but it's pretty ugly and way too verbose for my liking. Any simpler way to do this using only STL functions?
Upvotes: 10
Views: 7802
Reputation: 38315
When you cannot use {fmt} or wait for C++20 <format>
, you at least want to delay the invocation of cout()
on durations as much as possible. Also, let <chrono>
handle the computation for you. Both measures improve the terseness of the snippet:
const auto hrs = duration_cast<hours>(sysInactive);
const auto mins = duration_cast<minutes>(sysInactive - hrs);
const auto secs = duration_cast<seconds>(sysInactive - hrs - mins);
const auto ms = duration_cast<milliseconds>(sysInactive - hrs - mins - secs);
And the output:
cout << "System inactive for " << hrs.count() <<
":" << mins.count() <<
":" << secs.count() <<
"." << ms.count() << endl;
Note that you could also define a utility template,
template <class Rep, std::intmax_t num, std::intmax_t denom>
auto chronoBurst(std::chrono::duration<Rep, std::ratio<num, denom>> d)
{
const auto hrs = duration_cast<hours>(d);
const auto mins = duration_cast<minutes>(d - hrs);
const auto secs = duration_cast<seconds>(d - hrs - mins);
const auto ms = duration_cast<milliseconds>(d - hrs - mins - secs);
return std::make_tuple(hrs, mins, secs, ms);
}
that has a nice use case in conjunction with structured bindings:
const auto [hrs, mins, secs, ms] = chronoBurst(sysInactive);
Upvotes: 16