c++ compare time

#include <iostream>
#include <chrono>

int main() {
    std::chrono::time_point<std::chrono::system_clock> start, end;

    start = std::chrono::system_clock::now();

    // Perform some operation here (for example, a loop)
    for (int i = 0; i < 1000000; ++i) {
        // Do something
    }

    end = std::chrono::system_clock::now();

    std::chrono::duration<double> elapsed_seconds = end - start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);

    std::cout << "Elapsed time: " << elapsed_seconds.count() << "s\n";

    return 0;
}

Explanation: - #include <iostream>: Includes the standard input/output stream header file for input and output operations. - #include <chrono>: Includes the header file for the C++ time utilities. - std::chrono::time_point<std::chrono::system_clock> start, end;: Declares two time points named start and end using the std::chrono::time_point template with std::chrono::system_clock as the clock type.

  • start = std::chrono::system_clock::now();: Retrieves the current time using std::chrono::system_clock::now() and assigns it to the start time point.

  • for (int i = 0; i < 1000000; ++i) { / Do something / }: Represents a placeholder loop where an operation could be performed. In this example, the loop runs 1,000,000 times, simulating some computational work.

  • end = std::chrono::system_clock::now();: Retrieves the current time again using std::chrono::system_clock::now() and assigns it to the end time point after the loop execution.

  • std::chrono::duration<double> elapsed_seconds = end - start;: Calculates the duration between start and end time points and stores it in the variable elapsed_seconds. The duration is measured in seconds.

  • std::time_t end_time = std::chrono::system_clock::to_time_t(end);: Converts the end time point to a std::time_t representation.

  • std::cout << "Elapsed time: " << elapsed_seconds.count() << "s\n";: Prints the elapsed time by retrieving the count of elapsed seconds from elapsed_seconds and displaying it as part of the output.

  • return 0;: Indicates successful program execution by returning 0 to the operating system.