Skip to content

Instantly share code, notes, and snippets.

@kantoniak
Last active April 13, 2017 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kantoniak/b0e5f64c4ef8f2926dc18c201d9dcbb8 to your computer and use it in GitHub Desktop.
Save kantoniak/b0e5f64c4ef8f2926dc18c201d9dcbb8 to your computer and use it in GitHub Desktop.
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