Chrono and Formatting

Chrono and Formatting

Durations, clocks, time points, and modern text formatting in one quick reference.

Chrono and Formatting

Durations and clocks

using namespace std::chrono_literals;

auto timeout = 250ms;
auto start = std::chrono::steady_clock::now();

Pick the clock by the question

Quick clock comparison

Measuring elapsed time

auto start = std::chrono::steady_clock::now();
do_work();
auto end = std::chrono::steady_clock::now();
auto elapsed = end - start;
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(elapsed);
std::cout << "work took " << ms.count() << " ms\n";

Converting durations

auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(elapsed);

Use duration_cast when you need an explicit unit. Keep the original duration type if precision matters.

std::format and std::print

auto msg = std::format("{} took {} ms", name, ms.count());
std::print("{}\n", msg);

Formatting dates and times

auto now = std::chrono::system_clock::now();
auto text = std::format("{:%Y-%m-%d %H:%M}", now);

This is much easier to read and maintain than manually stitching together date fields.

Common format patterns

std::format("{:%H:%M:%S}", now);
std::format("{:%Y-%m-%d}", now);
std::format("elapsed = {} ms", ms.count());

Formatting your own types

If you format the same domain type repeatedly, consider defining a std::formatter specialization so logging and diagnostics stay consistent.

Practical guidance

Quick decision guide

Real-world pattern: measure and report

auto start = std::chrono::steady_clock::now();
run_job();
auto elapsed = std::chrono::steady_clock::now() - start;

std::print("job finished in {} ms\n",
		   std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count());

Pitfalls worth remembering

Two common workflows

auto deadline = std::chrono::steady_clock::now() + 500ms;
while (std::chrono::steady_clock::now() < deadline) {
	if (poll_ready()) {
		break;
	}
}

Use this shape for timeout logic.

auto now = std::chrono::system_clock::now();
std::print("backup finished at {:%F %T}\n", now);

Use this shape for logs and user-visible timestamps.

Example in practice

#include <optional>

std::optional<int> value() {
    return 42;
}

Try this variation

Swap one older pattern for a newer standard facility, then compare clarity. This keeps modern C++ grounded in practical tradeoffs instead of feature tourism.

#include <format>
#include <string>

int main() {
    std::string line = std::format("{} items ready", 3);
    return static_cast<int>(line.size());
}