如何及时执行if语句?

How to execute if statement in time?

本文关键字:if 语句 执行      更新时间:2023-10-16

我以这种方式减慢了 if 语句的执行速度。但我不喜欢他。

for (size_t i = 0;;) {
i = (i + 1) % 1000000;
if (i == 10) {
cout << " TEST " << "n" << endl;
}
}

我想按时制作代码。 在一分钟过去之前,应始终传递 if 语句。

如何实现这一点?

for (;;) { 
/* do something */ 
if (one_minute_elapsed_since_first_iteration) { 
/* do something else */ 
} 
}

还有一个问题,它会比第一个选项工作得更快吗?

如果你只是想在你的if中添加延迟,那么 std::this_thread::sleep_for 可能是你想要的。它会让您的代码进入睡眠状态一段时间,然后在时间到期后继续运行。

例如,要睡一分钟,你可以这样做

#include <chrono>
#include <thread>
...
using namespace std::chrono_literals;
...
std::this_thread::sleep_for(1m);

要回答更新的问题:

"这怎么可能实现?

for (;;) { /* do something */ if (one_minute_elapsed_since_first_iteration) { /* do something else */ } }">

您需要在循环开始时获取时间戳,然后检查是否超过所需时间。例如:

#include <chrono>
using namespace std::chrono_literals;
auto start = std::chrono::steady_clock::now();
for (;;) {
/* Do something */
auto now = std::chrono::steady_clock::now();
if (std::chrono::duration_cast<std::chrono::seconds>(now - start) >= 60s) {
/* Do something else */
/* If we should again wait 1 min. Reset start time */
start = std::chrono::steady_clock::now();
}
}