【发布时间】:2012-11-27 23:24:21
【问题描述】:
所以我试图使用 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]);
}
}
问题是,它只是精确地输出 3000 毫秒,而实际上显然不是这样。
在较短的问题上,它只输出 0ms...我做错了什么?
编辑:如果有任何用处,我正在使用带有 -std=c++0x 标志的 GNU GCC 编译器
【问题讨论】:
-
在我的 windows 框中,它使用 MSVC 17.00.50727.1 (VSExpress2012) 和 GCC 4.8.0 20120924 报告准确的时间
-
Nitpick:更喜欢
typedef std::chrono::high_resolution_clock timer; auto start_time = timer::now();因为 now() 是静态成员 -
我看不出代码有什么问题,对于较短的时间,您可能只需将句点更改为
std::nano等。 -
嗯,定时器的实际滴答周期是未指定的。您将其转换为毫秒(顺便说一句,您可以只使用预定义的持续时间
std::chrono::milliseconds)但它可以是任何东西。如果周期是秒,那么预计会得到 1000 的精确倍数。 (当然 high_resolution_clock 希望使用更小的周期,而 IIRC libstdc++ 使用纳秒...) -
其实你目前使用的duration-cast可以对你得到的时间有影响,因为你投到
duration<int,milli>,这意味着用于内部的类型时间表示变为int。在int很小的平台上,这可能会导致问题。如果你真的想选择自己的表现类型,intmax_t会是更好的选择。