1

I would like to calculate the time it takes (in nanoseconds) to execute a function. I know this might be a duplicate question but I could not find a solution anywhere. I already have a working calculation for milliseconds (it was taken from MSDN):

QueryPerformanceFrequency(&freq); 
QueryPerformanceCounter(&begin);

callfunction();

QueryPerformanceCounter(&end);
elapsed.QuadPart = (end.QuadPart - begin.QuadPart);
elapsed.QuadPart *= 1000000.0;
elapsed.QuadPart /= freq.QuadPart;

I tried doing something on the same idea to be able to achieve a nanosecond result, but to no avail. I already have this implemented in linux using the function clock_gettime().

Also the code is being written in C and not in C++.

Thanks for the help.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Jean Claude Abela
  • 782
  • 1
  • 9
  • 26
  • The return value of QueryPerformanceFrequency() depends on your motherboard design. Always at least a million. Getting down to nanosecond resolution typically requires a cheap one that uses the processor clock. Pretty meaningless, such a frequency source is quite inaccurate. And unnecessary, a modern processor is not nearly deterministic enough. – Hans Passant Mar 17 '16 at 15:38
  • https://stackoverflow.com/questions/5404277/porting-clock-gettime-to-windows (and/or https://stackoverflow.com/questions/275004/timer-function-to-provide-time-in-nano-seconds-using-c) – pmg Mar 17 '16 at 15:39

1 Answers1

1

The interrupts and reading the hardware clock don't work to that fine a degree.

You can profile a routine and it will effectively give you percentage of how long it is in each function. If you know how many times the function is called and how long the code was running as a whole you can get an approximate idea.

AnthonyLambert
  • 8,768
  • 4
  • 37
  • 72