Search code examples
c++visual-studio-2008timing

Timing program runtimes in visual C++


Is there a quick and easy way of timing a section of a program (or the entire thing) without having to setup a timer class, functions, and variables inside my program itself?

I'm specifically referring to Visual C++ (Professional 2008).

Thanks,

-Faken

Edit: none of these answers do what i ask for, i would like to be able to time a program inside visual c++ WITHOUT having to write extra bits of code inside it. Similar to how people do it with BASH in Linux.


Solution

  • In the Intel and AMD CPUs there is a high speed counter. The Windows API includes function calls to read the value of this counter and also the frequency of the counter - i.e. how many times per second it is counting.

    Here's an example how to time your time in microseconds:

    
    #include <iostream>
    #include <windows.h>
    
    int main()
    {
            __int64 ctr1 = 0, ctr2 = 0, freq = 0;
    
            // Start timing the code.
    
            if (QueryPerformanceCounter((LARGE_INTEGER *) &ctr1) != 0) {
                    // Do what ever you do, what ever you need to time...
                    //
                    //
                    //
    
                    // Finish timing the code.
    
                    QueryPerformanceCounter((LARGE_INTEGER *) &ctr2);
                    QueryPerformanceFrequency((LARGE_INTEGER *) &freq);
    
                    // Print the time spent in microseconds to the console.
    
                    std::cout << ((ctr2 - ctr1) * 1.0 / freq) << std::endl;
            }
    }