How can I calculate the time of the programs, for example, bubble sorting?

  • one
    For example, see clock . In C ++, any timers are better developed, of course ... but you can use the operating system API. - Harry
  • @ Harry.a if not Linux, but Windows? - Elvin
  • one
    And clock does not depend on OSes :) And in Windows there is such a great pair of QueryPerformanceCounter - QueryPerformanceFrequency ... - Harry
  • @ Harry, I see only their use in C ++, but not in C - Elvin
  • What's the difference? ... - Harry

1 answer 1

Well, here's an example on pure C, like this:

 #include <stdio.h> #include <windows.h> long long getFreq() { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return f.QuadPart; } long long muTime() { static long long freq = 0; if (freq == 0) freq = getFreq(); LARGE_INTEGER t; QueryPerformanceCounter(&t); return (t.QuadPart * 1000000L)/freq; } int main() { long long start = muTime(); Sleep(1000); long long stop = muTime(); printf("%lld mks\n",stop-start); } 

Time measurement in microseconds.

Just keep in mind that a bunch of different factors can affect measurements, so it’s better to do a lot of measurements, and the function itself, let's say, cause a cycle many times, and then divide the total time by the number of iterations — well, so that random factors can be eliminated

  • QueryPerformanceCounter() is still WINAPI, not pure C ... - Fat-Zer
  • And we discussed this in the comments to the question - the TS asked about Windows, I answered, he asked for an example ... See for yourself how the discussion developed ... - Harry
  • Yes, I saw it, but it doesn’t become “pure C”;) - Fat-Zer
  • I generally hinted that in the answer the words about “pure C” should be corrected)) Fat-Zer