Ziggy
Ziggy

Reputation: 22375

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

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!

Upvotes: 2

Views: 1784

Answers (5)

shiney
shiney

Reputation: 13

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

Upvotes: 0

David Grayson
David Grayson

Reputation: 87406

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.

Upvotes: 2

vines
vines

Reputation: 5225

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

Upvotes: 2

smparkes
smparkes

Reputation: 14063

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.

Upvotes: 4

Wyzard
Wyzard

Reputation: 34563

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.

Upvotes: 6

Related Questions