I am wanting to time my insertion sort. If I have the code like this it works, but it prints once for every sort in the loop (because it's in the loop):
clock_t start;
double duration;
start = clock();
int j, temp;
for (int i = 0; i < NumberOfLines; i++) {
j = i;
while (j > 0 && arr[j - 1] < arr[j]) {
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
j--;
}
duration = (clock() - start) / (double)CLOCKS_PER_SEC;
cout<<"Sorting took: "<< duration<<" seconds"<<'\n';
}
duration = (std::clock() - start) / (double)CLOCKS_PER_SEC;
cout << "Please Work: " << duration << " seconds" << '\n';
But If I comment the cout
inside the loop, it returns 0 time taken:
duration = (clock() - start) / (double)CLOCKS_PER_SEC;
//cout<<"Sorting took: "<< duration<<" seconds"<<'\n';
}
duration = (std::clock() - start) / (double)CLOCKS_PER_SEC;
cout << "Please Work: " << duration << " seconds" << '\n';
Why?