Timing sorting algorithms

closed account (4ET0pfjN)
Hi, I need to time sorting algorithms that I wrote, I wonder if there is better way to go more accurate like 2 decimal places, this is what I have so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <ctime>
#include <iostream>
using namespace std;

int main()
{
	clock_t startTime = clock();
	int arraySize = 100000; 
	int *insertionList = createArray(arraySize);
	
	//sort this list
	insertionSort(insertionList, arraySize);//my insertion sort fcn
	
	clock_t endTime = clock();
	clock_t duration = (endTime - startTime)/CLOCKS_PER_SEC;
	cout<<"Elapsed time: "<<duration*1000<<" ms"<<endl;

	return 0;
}


I'm getting 11000 ms, the reason I ask is b/c I need to compare the running time for my own implementation of the classic sorting algorithms.
Last edited on
You're performing integer division, so make sure you use floating point numbers throughout, e.g.

1
2
clock_t duration = double(endTime - startTime)/CLOCKS_PER_SEC*1000;
cout << "Elapsed time: " << duration << " ms" << endl;
There is a high resolution timer on most modern PCs.

If you're developing on Windows, look at GetPerformanceFrequency and GetPerformanceCounter.

I don't know if linux/unix has anything similar.
Last edited on
It's QueryPerformanceFrequency and QueryPerformanceCounter.
On Unices, there's clock_gettime() for high resolution measurements.

However, if milliseconds are not sufficient, then you're usually better off repeating your function for a few thousand/million times, which usually leads to far more accurate results.
Sorry about getting the names wrong. It's been a while since I pulled them up and was working off memory(obviously mine has a leak).
Topic archived. No new replies allowed.