Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of std::chrono durations.
#include <chrono>
#include <iostream>
using namespace std::literals::chrono_literals;
int main() {
{
// Implicit casting down
auto hours = 24h;
std::chrono::minutes minutes = hours;
std::chrono::seconds seconds = hours;
std::chrono::microseconds microseconds = hours;
std::chrono::nanoseconds nanoseconds = hours;
std::cout << hours.count() << "h" << std::endl
<< minutes.count() << "min" << std::endl
<< seconds.count() << "s" << std::endl
<< microseconds.count() << "ms" << std::endl
<< nanoseconds.count() << "ns" << std::endl
<< std::endl;
}
{
// Explicit casting up
std::chrono::seconds seconds{2400};
std::chrono::minutes minutes = std::chrono::duration_cast<std::chrono::minutes>(seconds);
std::cout << minutes.count() << "min" << std::endl << std::endl;
}
{
// Duration arithmetic
auto sum = 3h + 52min + 40s - 2ns; // will return ns as most precise
std::cout << "3h + 52min + 40s - 2ns = " << sum.count() << "ns" << std::endl << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.