8

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Gilzy
  • 103
  • 1
  • 1
  • 4

1 Answers1

19

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.

ForceBru
  • 43,482
  • 10
  • 63
  • 98