所以我试图使用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',等等。 –