要在 C 中睡眠,我应该使用 while 与时钟还是系统调用?
我正在查看cplusplus.com 上的clock()。他们的示例涉及让进程等待一秒钟,然后循环输出一行,直到 10 秒过去。我需要在我正在做的家庭作业中做类似的事情。我想知道的是:如果我只是将程序发送到循环中,那不是使用系统资源来让我旋转吗?在这种情况下,系统调用不是更好吗?
感谢您的帮助!
I was checking out clock() on cplusplus.com. Their example involves making the process wait for a second and then output a line, in a loop until 10 seconds have ellapsed. I need to do something similar in the homework assignment I'm working on. What I was wondering was this: if I just send my program into a loop, isn't that using system resources to just spin me around? In this case, wouldn't a system call be better?
Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您的程序是多线程的,那么最好使用
sleep()
。原因是clock()
在使用sleep()< 时需要额外的编码/code> 你可以用更少的内存和更少的时间来完成你的任务...
clock()
将涉及CPU很多...If your programme is multithreaded then better you go with
sleep()
.The reason isclock()
will need extra coding for that while by usingsleep()
you can do your task with less memory and less time...clock()
will involve CPU a lot...是的,使用系统调用或像
sleep()
这样的库函数要好得多。该clock()
示例只是为了展示如何正确调用该函数并解释其返回值,而不是说明让程序等待的最佳方法。Yes, using a system call or library function like
sleep()
is much better. Thatclock()
example is just meant to just show how to correctly call the function and interpret its return value, not to illustrate the best way to make a program wait.这是一个奇怪的例子。我知道这只是一个例子,但是......
要睡觉,请调用
sleep(unsigned int)
。还有其他用于亚秒级睡眠的调用(unix-y 机器上的
nanosleep
)。如果您是老派,则可以随时使用select()
。请注意,所有这些都可以被中断,因此如果由于某种原因它们提前返回,您可能需要循环。
That is a weird-ass example. I know it's just an example but ...
To sleep, call
sleep(unsigned int)
.There are other calls (
nanosleep
on unix-y machines) for sub-second sleeps. And you can always useselect()
if you're old school.Note that all of these can be interrupted so you may need to loop if for some reason they return early.
我必须补充一点,
sleep()
仅使当前线程进入睡眠状态,而不是整个程序(如果它是多线程的)。I have to add to the aforementioned that
sleep()
only puts the current thread to sleep, not the whole program, if it's multithreaded.需要明确的是,您不应该执行类似示例的操作。如果这样做,您的程序在等待时将消耗其中一个核心上 100% 的 CPU。最好使用
sleep
或select
之类的东西。Just to be clear, you should NOT do something like the example. If you do, your program will consume 100% of the CPU on one of the cores while it is waiting. It is much better to use something like
sleep
orselect
.