Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate execution time in milliseconds [duplicate]

Tags:

c++

I'm pretty new to C++, I need to print the execution time of my program in milliseconds with 4 digits (X.XXX) - I tried to use

double start_s=clock();
// my program here
double stop_s=clock();
cout << "time: " << (stop_s) << endl;

I got 0. What am I doing wrong? Btw I am using (and have to use, college project) VS2010, so chrono is not an option.

like image 954
Gilzy Avatar asked Mar 16 '16 17:03

Gilzy


1 Answers

Use std::chrono::high_resolution_clock from the chrono header.

auto started = std::chrono::high_resolution_clock::now();
DoWork();
auto done = std::chrono::high_resolution_clock::now();

std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(done-started).count();

You can also cast to std::chrono::seconds or std::chrono::nanoseconds if you wish.

Here's a tutorial on measuring execution time with chrono.


Edit: if your compiler doesn't support chrono, then get a newer one take a look at src/ptimer.c in the source code of wget. It works on Windows and Linux and uses native API.

like image 124
ForceBru Avatar answered Oct 04 '22 04:10

ForceBru