5

Is there a better function or way to measure time than clock() function on Windows? I have a short operation and when I try clock() or gettickcount() it says it took 0.0 seconds. I need a way to measure it by miliseconds or nanoseconds.

bash.d
  • 13,029
  • 3
  • 29
  • 42
Bar
  • 351
  • 3
  • 6
  • 18

2 Answers2

14

You can use QueryPerformanceCounter and QueryPerformanceFrequency :

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

int main(void)
{
    LARGE_INTEGER frequency;
    LARGE_INTEGER start;
    LARGE_INTEGER end;
    double interval;

    QueryPerformanceFrequency(&frequency);
    QueryPerformanceCounter(&start);

    // code to be measured

    QueryPerformanceCounter(&end);
    interval = (double) (end.QuadPart - start.QuadPart) / frequency.QuadPart;

    printf("%f\n", interval);

    return 0;
}
masoud
  • 55,379
  • 16
  • 141
  • 208
  • This worked with sequential search code. But it gives program stopped running error when i use it with a "Binary Search" code. What could be the problem? – Bar Mar 30 '13 at 16:31
  • Above code is tested, if you have problem, it's somewhere else. Debug your "Binary Search"... or, [ask your problem as a new StackOverflow question](http://stackoverflow.com/questions/ask). – masoud Mar 30 '13 at 16:34
  • 2
    `interval` should be in seconds (according to [this answer](https://stackoverflow.com/a/1739265) and [`QueryPerformanceFrequency`'s documentation](https://msdn.microsoft.com/de-de/library/windows/desktop/ms644905.aspx)) – pcworld Dec 02 '16 at 00:55
  • Note that frequency could be 0 if the hardware doesn't support it. So it's probably best to add a check that it isn't 0, – Tal Jerome Apr 20 '20 at 00:54
  • In MSVC I understand that `clock()` gives wall time not execution time. I tried this QPC method in the hope of getting consistent timings (for profiling), but sadly the measured time varies here too. This is for periods of 1 second or more, and for operations that are exactly the same on each run, so it can't be measuring execution time. So I still have to make several runs and record the shortest time. – Weather Vane Aug 08 '20 at 11:33
0

You can use QueryPerformanceCounter combined with QueryPerformanceFrequency to get nanosecond precision.