要在 C 中睡眠,我应该使用 while 与时钟还是系统调用?

发布于 2024-12-29 13:50:42 字数 249 浏览 5 评论 0原文

我正在查看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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

孤单情人 2025-01-05 13:50:43

如果您的程序是多线程的,那么最好使用 sleep()。原因是 clock() 在使用 sleep()< 时需要额外的编码/code> 你可以用更少的内存和更少的时间来完成你的任务... clock() 将涉及CPU很多...

If your programme is multithreaded then better you go with sleep().The reason is clock() will need extra coding for that while by using sleep() you can do your task with less memory and less time... clock() will involve CPU a lot...

葬花如无物 2025-01-05 13:50:42

是的,使用系统调用或像 sleep() 这样的库函数要好得多。该 clock() 示例只是为了展示如何正确调用该函数并解释其返回值,而不是说明让程序等待的最佳方法。

Yes, using a system call or library function like sleep() is much better. That clock() 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.

萝莉病 2025-01-05 13:50:42

这是一个奇怪的例子。我知道这只是一个例子,但是......

要睡觉,请调用 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 use select() 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.

源来凯始玺欢你 2025-01-05 13:50:42

我必须补充一点,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.

踏雪无痕 2025-01-05 13:50:42

需要明确的是,您不应该执行类似示例的操作。如果这样做,您的程序在等待时将消耗其中一个核心上 100% 的 CPU。最好使用 sleepselect 之类的东西。

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 or select.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文