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>
.
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";
This is what Python would call time.time()
.
double seconds = std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
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.)
you're a beast