在指定的时间段内运行函数:带有< chrono>的C ++; [英] Running a function for specified duration : C++ with <chrono>
本文介绍了在指定的时间段内运行函数:带有< chrono>的C ++;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要实现一个函数,该函数应在指定的持续时间内执行指定的任务,并将其作为参数(std :: chrono :: milliseconds)
传递给它。
I need to implement a function that should do specified task for specified duration which is passed to it as parameter (std::chrono::milliseconds)
.
我想出了代码:
void Run(std::chrono::milliseconds ms)
{
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
while (elapsed_seconds <= (ms / 1000))
{
std::cout << "Running" << std::endl;
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
}
}
int main()
{
{
std::chrono::milliseconds ms(30000);
Run(ms);
system("Pause");
}
我想打印运行$的代码c $ c> 30秒钟,然后退出。但是它没有这样做。如何使用
C ++< chrono>
I suppose the code to print Running
for 30 seconds and then exit. But it does not do so. How do I achieve such behavior with C++ <chrono>
推荐答案
您真正需要做的就是知道 end
点,然后循环直到达到该点:
All you really need is to know the end
point and then loop until that point is reached:
#include <chrono>
void Run(std::chrono::milliseconds ms)
{
std::chrono::time_point<std::chrono::system_clock> end;
end = std::chrono::system_clock::now() + ms; // this is the end point
while(std::chrono::system_clock::now() < end) // still less than the end?
{
std::cout << "Running" << std::endl;
}
}
int main()
{
std::chrono::milliseconds ms(3000);
Run(ms);
system("Pause");
}
这篇关于在指定的时间段内运行函数:带有< chrono>的C ++;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文