-2

I am trying to compare two sorting algorithms merge sort and quick sort by seeing which one takes the least amount of time sorting a small integer array like {8,7,6,5,4,3,2,1} I know I shouldnt use clock() and I've been trying time() but every time it keeps giving me 0 for the time taken. I've tried using Chrono as well and it also just gives me 0 Can someone help me out with this?

The sorts are already made and they work fine, this is how I have it setup.

int Quiarr[] = {8, 7, 6, 5, 4, 3, 2, 1};
int arr_size = sizeof(Quiarr)/sizeof(Quiarr[0]);
start = time();
mergeSort(Quiarr, 0, arr_size - 1);
end = time();
msecs = ((double) (end - start)) * 1000 / CLOCKS_PER_SEC;
cout << msecss2 << " " << endl;

1 Answers1

0

try this

auto t0 = std::chrono::high_resolution_clock::now();
// your sorting function here
auto t1 = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1);

high_resolution_clock::now(), has a precise granularity.

NOTE: you need to run more than one trial of your function, that's because of the OS scheduler, the elapsed time is not constant, and you need to consider the smallest value you get. (run a loop that repeats the code above let say 1000 times, and print the elapsed time the smallest value that repeats the most is the more plausible one).

organicoman
  • 154
  • 6