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