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

2019-05-23 21:14发布

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!

5条回答
聊天终结者
2楼-- · 2019-05-23 21:32

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

查看更多
相关推荐>>
3楼-- · 2019-05-23 21:42

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.

查看更多
Juvenile、少年°
4楼-- · 2019-05-23 21:45

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

查看更多
霸刀☆藐视天下
5楼-- · 2019-05-23 21:53

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.

查看更多
Deceive 欺骗
6楼-- · 2019-05-23 21:57

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.

查看更多
登录 后发表回答