#include <iostream>
#include <chrono>
#include <thread>   // for std::this_thread::sleep_for
#include <iomanip>  // for std::put_time

int main() {
    // 1. Get current time point from system clock
    auto now = std::chrono::system_clock::now();
    // Convert to time_t for human-readable output
    std::time_t tt = std::chrono::system_clock::to_time_t(now);
    std::cout << "Current time: " << std::put_time(std::localtime(&tt), "%Y-%m-%d %H:%M:%S") << std::endl;

    // 2. High‑precision timing: measure execution time of a code block
    auto start = std::chrono::high_resolution_clock::now();

    // Simulate some work (e.g., a loop)
    volatile long long sum = 0;  // prevent compiler optimization
    for (int i = 0; i < 1000000; ++i) {
        sum += i;
    }

    auto end = std::chrono::high_resolution_clock::now();

    // Calculate elapsed time in different units
    auto duration_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);
    auto duration_us = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
    auto duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);

    std::cout << "Loop calculation took: "
              << duration_ns.count() << " nanoseconds, "
              << duration_us.count() << " microseconds, "
              << duration_ms.count() << " milliseconds" << std::endl;

    // 3. Use steady_clock for interval measurement (unaffected by system time adjustments)
    auto steady_start = std::chrono::steady_clock::now();
    std::this_thread::sleep_for(std::chrono::milliseconds(200));  // sleep for 200 ms
    auto steady_end = std::chrono::steady_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(steady_end - steady_start);
    std::cout << "Actually slept for " << elapsed.count() << " milliseconds" << std::endl;

    // 4. Custom duration units and arithmetic operations
    std::chrono::seconds sec(5);
    std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(sec);
    std::cout << "5 seconds = " << ms.count() << " milliseconds" << std::endl;

    // Add a duration to a time point
    auto future_time = now + std::chrono::hours(1);
    std::time_t future_tt = std::chrono::system_clock::to_time_t(future_time);
    std::cout << "One hour later: " << std::put_time(std::localtime(&future_tt), "%Y-%m-%d %H:%M:%S") << std::endl;

    return 0;
}

results matching ""

    No results matching ""