Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Last active August 29, 2015 13:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pyrtsa/9288950 to your computer and use it in GitHub Desktop.
Save pyrtsa/9288950 to your computer and use it in GitHub Desktop.
C++1y: Using user-defined literals for making `std::chrono::duration`s
#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;
}
@serpent
Copy link

serpent commented Mar 1, 2014

Use "\n" instead of "std::endl" to avoid superfluous flushing of the output stream.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment