I
I
IvankoPo2017-05-10 15:19:58
C++ / C#
IvankoPo, 2017-05-10 15:19:58

How to find out the execution time of a sort in C++?

In programming, a beginner, recently began to study sorting, the question arose of how to display the execution time of my sorting in the console.
What methods are there?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mercury13, 2017-05-10
@IvankoPo

Use either time.h from C or std::chrono from C++11. Here is an example for the second.

#include <iostream>
#include <chrono>

int main()
{
    using Time = std::chrono::time_point<std::chrono::high_resolution_clock>;
    using Diff = std::chrono::milliseconds;

    Time t1 = std::chrono::high_resolution_clock::now();
    int i;
    std::cin >> i;
    Time t2 = std::chrono::high_resolution_clock::now();
    Diff diff = std::chrono::duration_cast<Diff>(t2 - t1);
    std::cout << diff.count() << " ms" << std::endl;
    return 0;
}

M
Maxim Moseychuk, 2017-05-10
@fshp

const std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
my_sort();
const std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();

D
Dmitry, 2017-05-10
@TrueBers

Mercury13 and fshp answered correctly.
With only one exception: std::chrono::high_resolution_clock- not monotonous hours. That is, they can drift even relative to the RTC, and this drift will be corrected and affect the measurement results. For example, when you take measurements, and between start and stop, NTP synchronization will arrive to you.
You need to use a monotonous clock, for this purpose are intended std::chrono::steady_clock. They are independent of change and are specifically designed for span measurements.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question