1

I am trying to time the duration of various sorting algorithms and am using the following code to do so. It seems to work when I time a user input, but when I time the function, it always gives me 0. I started off with milliseconds, and then moved to microseconds and then nanoseconds.

Here is the code I am using:

auto t1 = std::chrono::high_resolution_clock::now();
quickSort(p, 0, numberofints-1);
auto t2 = std::chrono::high_resolution_clock::now();
cout << "quicksort took "<< std::chrono::duration_cast<chrono::nanoseconds>(t2-t1).count()<< " nanoseconds\n";
YSC
  • 38,212
  • 9
  • 96
  • 149
  • 1
    Are you sure your function takes more than 1 nano to execute? – SergeyA Dec 05 '16 at 16:39
  • 1
    Quicksort is, well, _quick_... – ForceBru Dec 05 '16 at 16:40
  • 1
    What's the size of `p`? – YSC Dec 05 '16 at 16:40
  • Could it be that the compiler is detecting that the quicksort call is unecessary and is removing it? Do you use the result of the sort anywhere? (outside of the timing window ofc) – Borgleader Dec 05 '16 at 16:41
  • I doubt you actually get nanosecond resolution from `std::chrono::high_resolution_clock`. See http://stackoverflow.com/q/16299029/10077 – Fred Larson Dec 05 '16 at 16:42
  • The size of the p array is 20 integers long. I can't say for certain how long it takes to evaluate but I'm sure it must take at least one millisecond. Also I looked into the resolution of the nanosecond. You are correct, it is not true nanoseconds. But even when tried at millisecond or microseconds, I am getting a value of 0. – Ferial Hillawi Dec 05 '16 at 18:03
  • Which compiler & version? Some are known to have more problems than others. Latest versions of the compilers tend to work better. – Howard Hinnant Dec 05 '16 at 18:20
  • Just in case, if you're running on Windows and using an older version of Visual Studio, std::chrono::high_resolution_clock just runs at the default clock rate of 64 hz or 15.625 ms per tick. [timeBeginPeriod](https://msdn.microsoft.com/en-us/library/windows/desktop/dd757624(v=vs.85).aspx) may be able to change this to 1000 hz == 1 ms. An alternative is [QueryPerformanceCounter](http://msdn.microsoft.com/en-us/library/windows/desktop/ms644904(v=vs.85).aspx) , which is at least 1 megahertz. – rcgldr Dec 05 '16 at 18:59
  • Here's how you can build your own `chrono` clock if what the std::lib gives you isn't satisfying. Building your own has problems too though. If it were easy, the std::lib one would be satisfying. ;-) – Howard Hinnant Dec 05 '16 at 22:41

0 Answers0