localhorst27
localhorst27

Reputation: 143

Weird behavior of QueryPerformanceCounter for measuring microseconds

I need to measure the performance of my written function. As I can't use C++11 and I need microseconds, I used QueryPerformanceCounter from windows.h.

#include <Windows.h>
LARGE_INTEGER begin, end, frequency;

double timeElapsed = 0.0;

QueryPerformanceFrequency(&frequency);

for (int i = 0; i < 100; i++) {
    QueryPerformanceCounter(&begin);

    myFunctionToTest();

    QueryPerformanceCounter(&end);

    // get microsecs
    timeElapsed = ((end.QuadPart - begin.QuadPart) * 1000.0 / frequency.QuadPart) * 1000;

    std::cout << timeElapsed << std::endl;

    appendToCsvFile(timeElapsed);
}

The results of timeElapsed usually are between 2 and 10 microseconds if I do NOT call appendToCsvFile().

Calling the function appendToCsvFile(), which does nothing than writing the result to a file, hugely affects the result of the measurement (results between 20 and 60 microseconds).

The function is called AFTER the measurement but it has some effect. Is there any reason how this is possible? Is there any library for Visual C++ 2010 which is appropriate for microsecond measurements?

Upvotes: 0

Views: 148

Answers (1)

Alan Birtles
Alan Birtles

Reputation: 36379

When measuring something in the microsecond range you need to expect weird things to happen.

There are many possible causes for this including:

  1. CPU caches being cleared by appendToCsvFile, without this call myFunctionToTest is using the same memory over and over resulting in a nice warm cache and better performance.
  2. When you write a file you trigger a whole series of actions which eventually result in the data ending up on your storage medium. Not all of these actions will be complete when control returns to your program resulting in extra background CPU usage which will slow down myFunctionToTest

Upvotes: 2

Related Questions