考虑以下代码,它将始终显示某些代码的最慢执行时间:
std::chrono::steady_clock::time_point begin, end
std::chrono::duration_cast<std::chrono::microseconds> lastElapsed;
begin = std::chrono::steady_clock::now();
... some processing to be measured ...
end = std::chrono::steady_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count();
if (elapsed > lastElapsed)
{
std::cout << "The slowest execution interval is now at " << elapsed << "us" << std::endl;
lastElapsed = elapsed;
}
我无法编译:
/home/user/dev/MyThread.cpp:104:59: error: expected ‘;’ before ‘lastElapsed’
std::chrono::duration_cast<std::chrono::microseconds> lastElapsed;
^
/home/user/dev/MyThread.cpp:104:70: error: statement cannot resolve address of overloaded function
std::chrono::duration_cast<std::chrono::microseconds> lastElapsed;
^
/home/user/dev/MyThread.cpp:114:19: error: ‘lastElapsed’ was not declared in this scope
if (elapsed > lastElapsed)
如何修复此间隔比较器并相应地设置lastElapsed
变量类型?
答案 0 :(得分:3)
首先,std::chrono::duration_cast
不是类型,它的函数返回持续时间,因此lastElapsed
的声明无效。你可以像这样解决它:
auto lastElapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin);
基本上使用值0初始化lastElapsed
。
然后当你计算elapsed
时使用相同的类型:
auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin);
不要打扰count()
成员函数,直到您需要输出值:
std::cout << "The slowest execution interval is now at " << elapsed.count() << " us" << std::endl;
答案 1 :(得分:1)
检查一下:
std::chrono::steady_clock::time_point begin, end;
std::chrono::microseconds lastElapsed;
begin = std::chrono::steady_clock::now();
//... some processing to be measured ...
end = std::chrono::steady_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin);
if (elapsed > lastElapsed)
{
std::cout << "The slowest execution interval is now at " << elapsed.count() << "us" << std::endl;
}
lastElapsed = elapsed;