Any way to time individual lines in c++?

Associate
Joined
18 Oct 2002
Posts
1,108
Location
Nottingham
Ive treid using the built in profiler in visual c++ and a range of other software and with none of them ive been able to time how long in milliseconds it takes for any line of code (and any code that line runs) to run. Any advice or ideas?
 
Im fairly sure you can use the function GetTickCount() to do this.

Code:
DWORD GetTickCount(void);

Afraid ive never used it myself, but im fairly sure you just call it before and after a line of code and the returned DWORD will be in milli seconds.

Hope thats some help.
 
GetTickCount wont work on most systems - its not standard c++ - its a Microsoft extension.

Better to throw together a DIY timing class. The constructor records the time at construction and then you have a member function, called TimeElapsed(), that takes the current time, and subtracts the start time to give an answer.

Note that standard c++ doesnt provide for great granularity, so if its a given function you want to time you'd be better off calling it, say, a million times and measuring the total time.

Alternatively, most compilers/ides can run a profiler, that will give coverage and timing info.
 
Most blocks of code will need a higher resolution than milliseconds. So in that case you will be forced to use a platform-specific method. For Windows you can use the QueryPerformanceTimer/QueryPerformanceFrequency Win32 APIs.
 
Back
Top Bottom