如果我想限制函数 f()
的调用,例如每 10 秒不少于一次,我会这样做:
while(true)
{
int start = get_seconds_elapsed();
f()
int end = get_seconds_elapsed();
while(end - start < 10)
{
end = get_seconds_elapsed()
}
}
当然,这样做的问题是它将占用其运行的处理器的一个完整核心。我的问题是,是否有其他处理器密集程度较低的方法可以做到这一点?
编辑:我的意思是每秒少于一次,我打错了。
最佳答案
"My question is, is there any other less processor intensive way I can go about doing this?"
在标准 C++ 中,您可以使用 std::thread::sleep_for()
,或std::this_thread::sleep_until
实现非忙等待。
"I meant no less than once per second"
根据他们的示例,要每秒执行不少于一次,您可以使用
using namespace std::literals;
std::this_thread::sleep_for(990ms); // Sleep for at least 990 milliseconds.
在上面的示例中,我取了一个低于 1 秒的值,因为该函数根据底层操作系统平台的不同而存在不准确的情况。这些具体可以达到多少取决于,但期望 10 毫秒的容忍度是一个很好的经验值。
关于c++ - 除了忙等待之外,是否还有其他处理器密集程度较低的方法来限制调用函数的速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28782589/