问题
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!
回答1:
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.
回答2:
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.
回答3:
I have to add to the aforementioned that sleep()
only puts the current thread to sleep, not the whole program, if it's multithreaded.
回答4:
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
.
回答5:
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...
来源:https://stackoverflow.com/questions/9042498/to-sleep-in-c-should-i-use-while-with-a-clock-or-a-system-call