Search code examples
cruntimemeasure

Measuring the exact run time in C


I have an assignment that asks me to measure the exact run time of a couple of programs. I am not sure how to do this, but I think it has something to do with time_start(); as I've seen this on the internet. What does time_start(); mean, and how do I use it to measure run time? I'm using Windows 7, and Dev C++ Compiler

Thank you


Solution

  • "Precise" time measurement requires to use operating system specific functions.

    Under Windows, you proably want to use the following function: (MSDN)

    BOOL WINAPI QueryPerformanceCounter(_Out_  LARGE_INTEGER *lpPerformanceCount);
    

    This function gives you a high-resolution counter of ticks since your application started. The interval between two ticks depends on your processor and might be retrieved using the following function: (MSDN)

    BOOL WINAPI QueryPerformanceFrequency(_Out_  LARGE_INTEGER *lpFrequency);
    

    So here is a snippet of code to get a precise value of the current time in seconds:

    double GetCurTime()
    {
        LARGE_INTEGER CounterFreq;
        QueryPerformanceFrequency(&CounterFreq);
    
        LARGE_INTEGER Counter;
        QueryPerformanceCounter(&Counter);
        return (double)Counter.QuadPart / (double)CounterFreq.QuadPart;
    }
    

    So to make a time measurement, call GetCurTime() at the beginning and call it again at the end, and take the difference between the two values.