#include &
#include &
#include&
using namespace std;

void QuickSort(int arr[],int lo,int hi)
{
if(lo&>=hi){return;}
int first=lo;
int last=hi;
int key=arr[lo];
while(last&>first)
{
while(first&=key)
--last;
arr[first] = arr[last];
while(first&&>n;
for(int i=0;i&

代碼如上,測量一個快排演算法的運行時間,最後出來總為0,是我的計時有問題呢還是電腦太快了??

謝謝大家的解答...中午睡了一覺起來1000個排序都能看到時間了 上午100000個都沒有時間.電腦有毒..


你選用的計時器貌似在windows上的精度為33ms(或者更低,反正不精確),我一般都是用另一個api獲取遠超乎你想像的精確度:QueryPerformanceFrequency,用法可以百度。

我一般就用這個東西優化我的演算法


如果是兼容C++11的編譯器,取時間的話用chrono吧……

關於時間複雜度,1微秒為10^-6秒,而講道理qsort這種東西呢是O(nlogn),10^6個數都不超過1秒,而10^5大體上應該也就100毫秒以內,扔進去十來個數應當只有數十微秒的計算時間。

要知道很多非常先進的OS里(對的就是說windows+cl組合),取到微秒級計時器是需要一些比較非常規手段的,而往往你取到的只是個毫秒計時器,有些所謂微秒級往往只是毫秒乘了個1000,幾乎完全沒有意義。


把數據量調大一些。還有 GetSystemTimeAsFileTime 可能精度不夠,如果需要精確計時使用 QueryPerformanceCounter 更佳。使用說明見QueryPerformanceCounter function,精度可以達到 &<1us

示例:

LARGE_INTEGER nf, n1, n2;
QueryPerformanceFrequency(nf); // 獲取計數器頻率
QueryPerformanceCounter(n1); // 獲取開始時間
// ...
QueryPerformanceCounter(n2); // 獲取結束時間
cout &(static_cast&(n2.QuadPart - n1.QuadPart) / nf.QuadPart * 1000000) &

n = 10000 時 GetSystemTimeAsFileTime QueryPerformanceCounter 測出來分別是 0us 和 1500us左右,這裡 GetSystemTimeAsFileTime 的精度已經不夠用了(話說兩個 dwLowDateTime 直接真的大丈夫么……以及 FILETME 的單位是100ns)。比 GetSystemTimeAsFileTime 精確到不知道那裡去了(逃

另外之前試過 std::chrono::high_resolution_clock *在某些實現中*似乎有的實現對於需要很精確測速的地方不夠,還得自己用 QueryPerformanceCounter 弄一個……可以參考一下 @Milo Yip 寫的 Timer 實現:https://github.com/miloyip/itoa-benchmark/blob/master/src/timer.h

附:用 QueryPerformanceCounter 實現符合concept TrivialClock的真·高精度時鐘與 std::chrono::high_resolution_clock 的對比

#include &
#include &
#include &

#include &

class HighResolutionClock {

public:

using rep = double;
using period = std::ratio&<1&>;
using duration = std::chrono::duration&;
using time_point = std::chrono::time_point&;

static constexpr bool is_steady = false;

static time_point now() {

LARGE_INTEGER nf, n;
QueryPerformanceFrequency(nf);
QueryPerformanceCounter(n);
return time_point(duration(static_cast&(n.QuadPart) / nf.QuadPart));

}

};

int main() {

auto t11 = std::chrono::high_resolution_clock::now();
auto t21 = HighResolutionClock::now();
for(int i = 0; i &< 100000; ++i); auto t12 = std::chrono::high_resolution_clock::now(); auto t22 = HighResolutionClock::now(); std::cout &(t12 - t11).count() &(t22 - t21).count() &

編譯器 GCC 5.1.0 ,關閉優化運行,輸出:

std::chrono::high_resolution_clock: 0us或1000us
HighResolutionClock: 在280us上下浮動


用 std::chrono::high_resolution_clock 來計時, 可以精確到us.

auto t1 = chrono::high_resolution_clock::now();

//TODO

auto t2 = chrono::high_resolution_clock::now();

auto time_span = chrono::duration_cast&&>(t2 - t1);

std::cout &


可以考慮試試Visual Studio 2015 Community這裡的這個功能


請自己計算一下100000的數據量,快排的時間複雜度為O(nlogn),算下來大概1660964,現在最垃圾的電腦1s也能跑1e8,也就是0.016s跑完,你電腦再稍微好一點就根本測不出來了。把數據量調到1e8,讓猴排教你做人(
連1s都沒有嗎?
代碼沒問題 而是運行過快無法統計時間的話 解決辦法是 多循環幾次
java寫的快排十萬個數據是5ms不到的樣子,而且還是幾年前的渣電腦,感覺應該是定時器精度不夠,數據量放大到千萬級別試試?
試試std::chrono::high_resolution_clock?
推薦閱讀:
相关文章