Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are several methods for computing the discrepancy in time using C++. Below are some examples:

Method 1: Using the chrono library

#include <iostream>
#include <chrono>

int main() {
    auto start = std::chrono::high_resolution_clock::now();

    // Code to measure time

    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> elapsed_time = end - start;

    std::cout << "Elapsed time: " << elapsed_time.count() << " seconds" << std::endl;

    return 0;
}

Method 2: Using the time.h library

#include <iostream>
#include <time.h>

int main() {
    clock_t start = clock();

    // Code to measure time

    clock_t end = clock();
    double elapsed_time = double(end - start) / CLOCKS_PER_SEC;

    std::cout << "Elapsed time: " << elapsed_time << " seconds" << std::endl;

    return 0;
}

Method 3: Using the gettimeofday function

#include <iostream>
#include <sys/time.h>

int main() {
    timeval start, end;

    gettimeofday(&start, NULL);

    // Code to measure time

    gettimeofday(&end, NULL);
    double elapsed_time = double(end.tv_sec - start.tv_sec) + double(end.tv_usec - start.tv_usec) / 1e6;

    std::cout << "Elapsed time: " << elapsed_time << " seconds" << std::endl;

    return 0;
}