To sleep in C, should I use while with a clock, or a system call?

空扰寡人 提交于 2019-12-06 05:35:23

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.

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.

I have to add to the aforementioned that sleep() only puts the current thread to sleep, not the whole program, if it's multithreaded.

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.

shiney

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!