How can I measure the execution time of a program in c++?

Asked

Viewed 2,720 times

0

I made a program that generates a vector randomly and then sorts it, using Bubble Sort, now I have to measure the time spent on sorting.

2 answers

3

You can calculate the runtime of functions using C++11 with high precision using the library <chrono>. Ex:

auto inicio = std::chrono::high_resolution_clock::now();
...SEU CÓDIGO AQUI...
auto resultado = std::chrono::high_resolution_clock::now() - inicio;
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(resultado).count();

Since you can replace std::chrono::microseconds (microseconds) by std::chrono::milliseconds (millisecond), std::chrono::seconds (seconds) or even std::chrono::nanoseconds (nanoseconds).

2

Are you using linux as OS? For a simple program like this I suggest you use time ./a.out at the terminal, where a.out is the executable of your program. This command prints 3 lines (explained briefly):

  • real: Real time from start to finish execution;
  • sys: Time spent by the system kernel in the process of running your program;
  • user: Time used in the user-mode. Is the time your computer spends in the out-of-kernel process;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.