0

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

Zeek
  • 11
  • 3
  • 3
    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 already loaded. – Anic17 Mar 04 '22 at 06:41
  • @Anic17 That could be posted as the answer to the question. – Lundin Mar 04 '22 at 07:30
  • 1
    https://stackoverflow.com/a/1639960/17034 – Hans Passant Mar 04 '22 at 13:03
  • @Zeek Have you got any updates? If your case has been solved, please help to mark answers. If not, just feel free to contact us. Your understanding and cooperation will be grateful. – Jeaninez - MSFT Mar 11 '22 at 08:46
  • @Jeaninez-MSFT Hadn't been on this account in a bit! I marked the answer as correct – Zeek Jun 06 '22 at 01:04

1 Answers1

1

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)

Anic17
  • 712
  • 5
  • 18