1

我必须计算冒泡排序需要多长时间并打印需要多长时间。在我的程序中,打印的时间始终为 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;
}
4

3 回答 3

6

我认为您需要使用比 difftime 更精确的东西(仅在几秒钟内报告):

有关更多信息,请参阅:C++ 中的时差。

于 2011-02-11T20:24:04.023 回答
4

它的执行速度比 cpu 时钟更新所需的速度快。你需要做的是执行你的排序几百万次,时间,然后将时间除以迭代次数(确保你使用双精度可以获得最高精度。所以基本上是这样的:

const int runs=1000000;
time(&start);

for(int r=0;r<runs;++r)
    bubbleSort(arr, 5000);

time(&end);
timeDiff = difftime(end, start);

double realduration=timeDiff/(double)runs;
于 2011-02-11T20:26:30.933 回答
0

5000 太小了,您需要运行整个排序过程 100 或 1000 次,然后除以该数字以获得一些时间

有人告诉我,要玩得开心,您需要让程序运行 5 到 10 秒

于 2011-02-11T20:27:49.370 回答