Skip to content

Instantly share code, notes, and snippets.

@mortie
Last active April 30, 2024 15:12
Show Gist options
  • Star 40 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mortie/bf21c9d2d53b83f3be1b45b76845f090 to your computer and use it in GitHub Desktop.
Save mortie/bf21c9d2d53b83f3be1b45b76845f090 to your computer and use it in GitHub Desktop.
std::chrono cheat sheet for the every-day programmer

Chrono cheat sheet

For the every-day programmer who needs to get shit done instead of fighting type errors.

If your application deals with times in any meaningful way, you should probably want to actually store time_points and durations and what-not; chrono has a pretty rich vocabulary for talking about time-related concepts using the type system. However, sometimes you just need to do something simple, like timing how long something takes, which is where chrono becomes overly complex, hence this cheat sheet.

All examples will assume #include <chrono>.

I just want to time something, then print the result

auto startTime = std::chrono::steady_clock::now();

/* something which might take time */

auto endTime = std::chrono::steady_clock::now();
auto duration = std::chrono::duration<double>(endTime - startTime);
std::cout << "It took " << duration.count() << " seconds.\n";

Alternatively, to print in milliseconds (or microseconds or gigaseconds or whatever):

auto startTime = std::chrono::steady_clock::now();

/* something which might take time */

auto endTime = std::chrono::steady_clock::now();
auto duration = std::chrono::duration<double, std::milli>(endTime - startTime); // or std::micro, std::giga, etc
std::cout << "It took " << duration.count() << " milliseconds.\n";

I just want to get a monotonically increasing time in seconds

This is what Python would call time.time().

double seconds = std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();

I just want to print a pretty datetime

In C++20, you should be able to do this:

std::cout << "Now: " << std::chrono::system_clock::now() << '\n';

However, until then you can convert it to a time_t and use ctime:

time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << "Now: " << ctime(&now) << '\n';

(note that ctime isn't thread-safe. Use ctime_r if you need a thread-safe variant.)

@ahmadjandal
Copy link

you're a beast

@oliver
Copy link

oliver commented Feb 14, 2024

Do you have a suggestion for the case of "I just want to print a pretty datetime, but will millisecond/microsecond precision"?

@romasvrd
Copy link

amazing, thank you good person

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