我需要从一段时间中获取耗时。
something.start()
auto start = std::chrono::steadyt_clock::now();
while(something->is_valid())
{
// getting frames
auto end = std::chrono::steady_clock::now();
auto diff = end - start;
// do something with the frames
if(diff % 3 == 0) { /* do something with the something */ }
}
但它会在我得到时间的每一毫秒内得到时间,而我的 if 语句运行得太多了。我不能使用 std::this_thread::sleep_for() 因为我需要捕捉每一帧。我怎样才能做到并行?
最佳答案
从 C++14 开始,您可以执行 diff >= 3s
来查看差异是否等于或大于三秒(参见 this duration literal reference)。
否则,如果您坚持使用 C++11,则使用 diff >= std::chrono::seconds(3)
。
请注意,这需要您在每次条件为真时重置 start
:
if (diff >= 3s)
{
start = end;
// Do something with the something...
}
这是必需的,因为差异可以保持等于 3
(因此 diff % 3s == 0
为真)长达整整一秒,这意味着您的"Do something..."部分会错误地执行很多次。
关于c++ - 在 C++ 中获取耗时仅几秒钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53704361/