Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to time how long functions take in C++? [duplicate]

Tags:

c++

timing

In C# I would fire up the Stopwatch class to do some quick-and-dirty timing of how long certain methods take.

What is the equivalent of this in C++? Is there a high precision timer built in?

like image 596
Mithrax Avatar asked Dec 08 '22 04:12

Mithrax


2 Answers

I used boost::timer for measuring the duration of an operation. It provides a very easy way to do the measurement, and at the same time being platform independent. Here is an example:

boost::timer myTimer;
doOperation();
std::cout << myTimer.elapsed();

P.S. To overcome precision errors, it would be great to measure operations that take a few seconds. Especially when you are trying to compare several alternatives. If you want to measure something that takes very little time, try putting it into a loop. For example run the operation 1000 times, and then divide the total time by 1000.

like image 175
LucTeo Avatar answered May 12 '23 04:05

LucTeo


I've implemented a timer for situations like this before: I actually ended up with a class with two different implemations, one for Windows and one for POSIX.

The reason was that Windows has the QueryPerformanceCounter() function which gives you access to a very accurate clock which is ideal for such timings.

On POSIX however this isn't available so I just used boost.datetime's classes to store the start and end times then calculated the duration from those. It offers a "high resolution" timer but the resolution is undefined and varies from platform to platform.

like image 24
jkp Avatar answered May 12 '23 03:05

jkp