在c中运行一段时间的无限循环
我想无限循环运行一段时间。基本上,我想要这样的东西
//do something
while(1){
//do some work
}
//do some other thing
,但我希望循环的运行时间是固定的,例如,循环可以运行 5 秒。 有人有主意吗?
I want to run an infinite loop for a while. Basically, i want to have something like this
//do something
while(1){
//do some work
}
//do some other thing
but i want the running time of the loop to be fixed, example, the loop could be running for 5 seconds.
Do somebody have an idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
只需执行
sleep(5)
(包括unistd.h
)。您可以这样使用它:如果您在循环内工作,您可以执行以下操作(包括
time.h
):Just do
sleep(5)
(includeunistd.h
). You can use it like this:If you're doing work inside the loop, you can do (include
time.h
):尝试使用时钟()。
Try using clock().
首先,如果可能的话,考虑使用
sleep
函数。如果您必须在指定的时间段内完成实际工作(我认为这不太可能),则以下丑陋的解决方案将起作用:使用
time.h
的解决方案也是可能的,并且可能更简单和/或更多种准确,取决于上下文:First of all, consider using the
sleep
function if possible. If you have to do actual work for a specified time period, which I find unlikely, the following ugly solution would work:A solution using
time.h
would also be possible, and perhaps simpler and/or more accurate, depending on context:伪代码:
Pseudo-code:
如果您不想每次通过循环调用时间获取函数并且在具有警报的系统上(POSIX,如 Unix、Linux、BSD...),您可以执行
以下操作 :整数超时= 0;
信号可能会产生其他副作用(例如将您踢出系统调用)。在依赖它们之前,您应该先研究一下它们。
If you don't want to call a time getting function each time through the loop and are on a system that has
alarm
(POSIXes like Unix, Linux, BSD...) you can do:static volatile int timeout = 0;
Signals can have other side effects (like kicking you out of system calls). You should look into these before relying on them.
未经测试;分辨率非常粗糙。
如果 /* work */ 花费超过 5 秒,则循环将花费超过 5 秒。
如果 /* work */ 需要 1.2 秒,则循环将执行大约 5 次,总共 6 秒
Not tested; resolution is very coarse.
If /* work */ takes more than 5 seconds, the loop will take more than 5 seconds.
If /* work */ takes 1.2 seconds, the loop will execute approximately 5 times for a total of 6 seconds