Last active
August 29, 2015 13:56
C++1y: Using user-defined literals for making `std::chrono::duration`s
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <chrono> | |
constexpr auto operator "" _days (unsigned long long n) { return std::chrono::hours(24 * n); } | |
constexpr auto operator "" _h (unsigned long long n) { return std::chrono::hours(n); } | |
constexpr auto operator "" _min (unsigned long long n) { return std::chrono::minutes(n); } | |
constexpr auto operator "" _s (unsigned long long n) { return std::chrono::seconds(n); } | |
constexpr auto operator "" _ms (unsigned long long n) { return std::chrono::milliseconds(n); } | |
constexpr auto operator "" _µs (unsigned long long n) { return std::chrono::microseconds(n); } | |
constexpr auto operator "" _ns (unsigned long long n) { return std::chrono::nanoseconds(n); } | |
// ... | |
#include <iostream> | |
#include <thread> | |
int main() { | |
auto t0 = std::chrono::steady_clock::now(); | |
std::cout << "Hello." << std::endl; | |
std::this_thread::sleep_for(1_s + 500_ms); | |
std::cout << "Still here." << std::endl; | |
std::this_thread::sleep_for(3 * 500_ms); | |
std::cout << "Bye." << std::endl; | |
auto t1 = std::chrono::steady_clock::now(); | |
std::cout << "(That took " << (t1 - t0) / 1_ns << " nanoseconds.)" << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use "\n" instead of "std::endl" to avoid superfluous flushing of the output stream.