[英]How to get approximate time, when an algorithm takes zero second/milli-second times?
我需要時間
我的快速排序過程在這里-
#include <bits/stdc++.h>
using namespace std;
int A[50000], i, j, V, store;
int part(int left, int right, int P)
{
V = A[P];
swap(A[P], A[right]);
store = left;
for(i = left; i < right; i++)
{
if(A[i] <= V)
{
swap(A[i], A[store]);
store++;
}
}
swap(A[store], A[right]);
return store;
}
void qSort(int left, int right)
{
if(left < right)
{
j = part(left, right, left);
qSort(left, j-1);
qSort(j+1, right);
}
}
main()
{
int nData, k, minValue, maxValue;
cout<<"No. of Data: ";
cin>>nData;
cout<<"\nRange (min, max): ";
cin>>minValue>>maxValue;
for(k=0; k<nData; k++)
{
A[k] = minValue + (rand()%(int) (maxValue - minValue + 1));
}
clock_t t1 = clock();
qSort(0, nData-1);
clock_t t2 = clock();
cout<<"\n\nTime: "<<(double)(t2-t1)/CLOCKS_PER_SEC<<endl;
}
[注意:我的操作系統是Windows]
main()
{
...
clock_t t1 = clock();
qSort(0, nData-1);
clock_t t2 = clock();
cout<<"\n\nTime: "<<(double)(t2-t1)/CLOCKS_PER_SEC<<endl;
}
這里的問題是,對於這種簡單的測試,編譯器太聰明了。 編譯器看到在程序中無效的代碼,它通過刪除不必要的代碼來優化程序。 您必須禁用優化(在調試模式下運行程序可能會這樣做)或修改程序,以便以某種方式使用排序操作的結果。
另外, clock()
在Windows和POSIX系統上具有不同的精度。 改用std::chrono
更為簡單。 例如
#include <iostream>
#include <chrono>
int main()
{
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
qSort(0, nData-1);
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "count:" << elapsed_seconds.count() << "\n";
return 0;
}
只需以足夠高的迭代次數在for循環中重復要測量的任務,然后將測量的時間除以迭代次數即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.