所以我試圖使用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中旗
在我的窗口框中,它報告使用MSVC 17.00.50727.1(VSExpress2012)和GCC 4.8.0 20120924 – sehe
的準確時間Nitpick:更喜歡'typedef std :: chrono :: high_resolution_clock timer; auto start_time = timer :: now();'as now()是靜態成員 – sehe
我沒有看到代碼有什麼問題,對於更短的時間,你可能只需要將句號改爲'std :: nano',等等。 –