冒泡排序的计时
我必须计算冒泡排序需要多长时间并打印它需要多长时间。在我的程序中,打印的时间始终为 0.00 秒。谁能告诉我我做错了什么?
int main()
{
srand((unsigned)time(NULL));
int arr[5000], arr2[5000];
int i;
time_t start, end;
double timeDiff;
for(i=0; i < 5000; i++)
{
arr[i] = rand() % 100 + 1;
arr2[i] = arr[i];
}
cout << "Here is the initial array:" << endl;
printArray(arr, 5000);
time(&start);
bubbleSort(arr, 5000);
time(&end);
timeDiff = difftime(end, start);
cout << "\nHere is the array after a bubble sort:" << endl;
printArray(arr, 5000);
cout << fixed << setprecision(2) << "\nIt took " << timeDiff << " seconds to bubble sort the array." << endl;
system("pause");
return 0;
}
I have to time how long a bubble sort takes and print how long it took. In my program the time printed is always 0.00 seconds. Can anyone tell me what I'm doing wrong?
int main()
{
srand((unsigned)time(NULL));
int arr[5000], arr2[5000];
int i;
time_t start, end;
double timeDiff;
for(i=0; i < 5000; i++)
{
arr[i] = rand() % 100 + 1;
arr2[i] = arr[i];
}
cout << "Here is the initial array:" << endl;
printArray(arr, 5000);
time(&start);
bubbleSort(arr, 5000);
time(&end);
timeDiff = difftime(end, start);
cout << "\nHere is the array after a bubble sort:" << endl;
printArray(arr, 5000);
cout << fixed << setprecision(2) << "\nIt took " << timeDiff << " seconds to bubble sort the array." << endl;
system("pause");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您需要使用比 difftime 更精确的东西(仅以秒为单位报告):
请参阅:C++ 中的时差了解更多信息。
I think you need to use something that has a little more precision than difftime (which only reports in seconds):
See: Time difference in C++ for more information.
它的执行速度比更新所需的 CPU 时钟速度还要快。你所要做的就是执行你的排序几百万次,计时,然后将时间除以迭代次数(确保使用双精度数以获得可以获得的最高精度。所以基本上是这样的:
It executes faster than the cpu clock takes to update. What you have to do is execute your sort a couple of million times, time that, and divide the time by the number of iterations (making sure you use a double for the most precision you can get. So basically something like:
5000 对于注册来说太小了,您需要运行整个排序过程 100 或 1000 次,然后除以该数字以获得一些时间
我被告知要获得一些好时间,您需要让程序运行 5 到 10 秒
5000 is to small to register you need to run the whole sorting process 100 or 1000 times then divide by that number to get some time
I was told that to get somewhat of a good time you need to have the program run for 5 to 10 sec