我在库中使用clock()来计算函数的执行时间,这是我下面代码中的BubbleSort(..)函数。但问题是返回执行时间总是= 0(并且它也没有显示任何单位)。 这是我的代码:
#include <iostream>
#include <ctime>
using namespace std;
void BubbleSort(int arr[], int n)
{
for (int i = 1; i<n; i++)
for (int j = n-1; j >=i; j-- )
if (arr[j] < arr[j-1])
{
int temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
return;
}
int main()
{
int arr[] = {4,1,7,2,6, 17, 3, 2, 8,1};
int len = sizeof(arr)/sizeof(int);
cout << "Before Bubble Sort: \n";
for (int i=0;i<len;i++)
{
cout << arr[i] << " ";
}
clock_t start_s=clock(); // begin
BubbleSort(arr,len);
clock_t stop_s=clock(); // end
cout << "\nAfter Bubble Sort: \n";
for (int i=0;i<len;i++)
{
cout << arr[i] << " ";
}
// calculate then print out execution time - currently always returns 0 and I don't know why
cout << "\nExecution time: "<< (double)(stop_s - start_s)/CLOCKS_PER_SEC << endl;
//system("pause");
return 0;
}
我还不知道如何解决这个问题..所以希望你们能帮我解决这个问题。任何评论都将非常感激。非常感谢先进!
答案 0 :(得分:3)
由于您只有一个非常小的数组,执行时间可能比clock()的分辨率短得多,因此您必须重复调用排序算法或使用其他时间源。
答案 1 :(得分:0)
我修改了你的代码,并且start end stop的值都为0.(ubuntu 13.10)
std::cout<<"start: "<<start_s<<std::endl;
BubbleSort(arr,len);
clock_t stop_s=clock(); // end
std::cout<<"stop: "<<stop_s<<std::endl;
你可能想要更像gettimeofday()
的东西这个http://www.daniweb.com/software-development/cpp/threads/120862/clock-always-returns-0是对同一件事的有趣讨论。海报的结论是,clock()(在他的机器上)的分辨率约为1/100秒。你的代码可能(几乎可以肯定)比那个
运行得更快