程序时间复杂度的测量

#include<time.h>
int main()
{
	int a[1000],step=10;
	double clocksPerMillis=double(CLOCKS_PER_SEC)/1000;
	for(int n=0;n<=1000;n+=step)
	{
		long numberOfRepeatitions=0;
		clock_t startTime=clock();
		do{
			numberOfRepeatitions++;
			for(int i=0;i<n;i++)
				a[i]=n-i;
			insertionSort(a,n);
		}while(clock()-startTime>1000);
		double elapseMillis=(clock()-startTime)/clocksPerMillis;
		if(n==100)step=100;
	}
	return 0;
}

思路很简单在在测量时间的算法前和后分别计算计算机的滴答数(时钟频率在开机后就一直运行)然后前后相减,得出算法运行时间,时钟滴答的次数,然后CLOCKS_PER_SEC是每秒滴答的次数,相处就得到秒数了,上面程序转换成了毫秒数。

上面程序对同一个n的计算算法重复了很多次计算,原因是一个计算时间太短,计算机滴答数的精度不够,所以多重复几次取平均,提高精度。

猜你喜欢

转载自blog.csdn.net/du_shuang/article/details/81042206