Is there a standard implementation to print std::duration
as a human readable duration?
steady_clock::time_point start = steady_clock::now();
doSomeFoo();
steady_clock::time_point end = steady_clock::now();
std::cout << "Operation took "
<< may_be_std::theMagic(start-end) << std::endl;
Which should print something similar to:
"Operation took 10d:15h:12m:14:s"
or something similar.
Based on Howard's answer, I wrote this to make sure that only the relevant data is printed out, so 120 seconds becomes 2m00s
instead of 00d:00h:02m00s
, and made sure to strip the leading zero, so its still 2m00s
and not 02m00s
.
Usage is simple:
std::chrono::seconds seconds{60*60*24 + 61};
std::string pretty_seconds = beautify_duration(seconds);
printf("seconds: %s", pretty_seconds.c_str());
>>seconds: 1d00h01m01s
Code:
std::string beautify_duration(std::chrono::seconds input_seconds)
{
using namespace std::chrono;
typedef duration<int, std::ratio<86400>> days;
auto d = duration_cast<days>(input_seconds);
input_seconds -= d;
auto h = duration_cast<hours>(input_seconds);
input_seconds -= h;
auto m = duration_cast<minutes>(input_seconds);
input_seconds -= m;
auto s = duration_cast<seconds>(input_seconds);
auto dc = d.count();
auto hc = h.count();
auto mc = m.count();
auto sc = s.count();
std::stringstream ss;
ss.fill('0');
if (dc) {
ss << d.count() << "d";
}
if (dc || hc) {
if (dc) { ss << std::setw(2); } //pad if second set of numbers
ss << h.count() << "h";
}
if (dc || hc || mc) {
if (dc || hc) { ss << std::setw(2); }
ss << m.count() << "m";
}
if (dc || hc || mc || sc) {
if (dc || hc || mc) { ss << std::setw(2); }
ss << s.count() << 's';
}
return ss.str();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With