2012-11-27 65 views
4

所以我試圖使用std :: chrono :: high_resolution_clock來計算執行時間需要多長時間。我計算過,你可以找到的開始時間和結束時間之間的區別...std :: chrono :: high_resolution_clock中的不準確性?

要檢查我的做法的作品,我做了以下程序:

#include <iostream> 
#include <chrono> 
#include <vector> 

void long_function(); 

int main() 
{ 
    std::chrono::high_resolution_clock timer; 
    auto start_time = timer.now(); 

    long_function(); 

    auto end_time = timer.now(); 
    auto diff_millis = std::chrono::duration_cast<std::chrono::duration<int, std::milli>>(end_time - start_time); 

    std::cout << "It took " << diff_millis.count() << "ms" << std::endl; 
    return 0; 
} 

void long_function() 
{ 
    //Should take a while to execute. 
    //This is calculating the first 100 million 
    //fib numbers and storing them in a vector. 
    //Well, it doesn't actually, because it 
    //overflows very quickly, but the point is it 
    //should take a few seconds to execute. 
    std::vector<unsigned long> numbers; 
    numbers.push_back(1); 
    numbers.push_back(1); 
    for(int i = 2; i < 100000000; i++) 
    { 
     numbers.push_back(numbers[i-2] + numbers[i-1]); 
    } 
} 

的問題是,它只是輸出3000ms確切地說,當它顯然不是那個時候。

在較短的問題,它只輸出0毫秒......我做錯了什麼?

編輯:如果它有什麼用途,我使用的GNU GCC編譯器-std = C++ 0x中旗

+0

在我的窗口框中,它報告使用MSVC 17.00.50727.1(VSExpress2012)和GCC 4.8.0 20120924 – sehe

+4

的準確時間Nitpick:更喜歡'typedef std :: chrono :: high_resolution_clock timer; auto start_time = timer :: now();'as now()是靜態成員 – sehe

+0

我沒有看到代碼有什麼問題,對於更短的時間,你可能只需要將句號改爲'std :: nano',等等。 –

回答

2

的high_resolution_clock的分辨率取決於平臺。

打印下面會給你下一個window7的執行決議的想法您使用

std::cout << "It took " << std::chrono::nanoseconds(end_time - start_time).count() << std::endl; 
1

我有相剋類似的問題++(rev5,由MinGW的-W64內置項目)4.8.1 。

int main() 
{ 
    auto start_time = std::chrono::high_resolution_clock::now(); 
    int temp(1); 
    const int n(1e7); 
    for (int i = 0; i < n; i++) 
     temp += temp; 
    auto end_time = std::chrono::high_resolution_clock::now(); 
    std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count() << " ns."; 
    return 0; 
} 

如果n = 1E7它顯示19999800納秒 但如果 N = 1E6顯示爲0毫微秒。

精度似乎很弱。

+0

你也應該把'temp'變量發送到std :: cout,否則,編譯器可能會把它和整個循環一起消除,巧妙地看到你沒有做任何事情。 –

+0

也許mingw的高分辨率時鐘在該版本上並不是真正的高分辨率。它看起來像1毫秒或2毫秒(n = 1e6)的數量可能最終爲零。也許重複這個措施會顯示出「爆發」,例如在10或15ms時,表示低分辨率約10-15ms(用linux的說法,窗口的默認「HZ」值) –

相關問題