开发者

Timing a Bubble Sort

I have to time how long a bubble sort takes and print 开发者_JAVA百科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;
}


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.


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:

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;


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜