Search code examples
cwindowswinapitimeperformancecounter

Incorrect QueryPerformanceCounter result or human error?


I have the following code for a C program that displays the number of microseconds it took for a system() call to run:

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


long long measure(char* command) {

// define variables
LARGE_INTEGER StartingTime, EndingTime, ElapsedMicroseconds;
LARGE_INTEGER Frequency;

// get the frequency of the counter
QueryPerformanceFrequency(&Frequency); 
// get the current count
QueryPerformanceCounter(&StartingTime);
// run our command
system(command);
// get the end of the count
QueryPerformanceCounter(&EndingTime);

// calculate the difference in counts
ElapsedMicroseconds.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart;

// scale to microseconds
ElapsedMicroseconds.QuadPart *= 1000000;
// divide by the frequency of the counter
ElapsedMicroseconds.QuadPart /= Frequency.QuadPart;
return ElapsedMicroseconds.QuadPart;

}

int main() {
    // measure the time it takes to run the command "ls"
    long long time = measure("echo hello");
    // print the time elapsed
    printf("%lld\n", time);
    return 0;
}

Now, when I run the program I get somewhere between 16-20 milliseconds when I do the math, however I get much lower times in PowerShell with Measure-Command {echo hello | Out-Default}. This leads me to suspect I am doing something wrong with QueryPerformanceCount. I am getting much larger timespans than I should be.

I attached an image of one of the instances showing a large difference.

Am I doing anything wrong with my code?

Thanks

Image showing a instance of the problem


Solution

  • Using system creates a new process, that's why it's taking longer.
    At the PowerShell example, you're not creating a new cmd.exe process, and performance is measured when PowerShell and all of its modules are already loaded.

    (Answer from my comment)