Using poll Instead of sleep to Delay a Program
12 May 2006, lunch time
The sleep()
function in C will delay your program for some number of seconds you specify. If you want to delay your program for some number of milliseconds, then clearly sleep()
will not work. A good alternative to sleep()
is the poll()
function. Normally, this is used to check if there is data to be read from a group of file descriptors; it can also double as simple sleep command. poll()
takes three parameters, an array of structures (struct *pollfd
), the number of elements in the array (unsigned int
), and the number of milliseconds to wait for data (int
). By ignoring the first two parameters, you can use poll()
as a higher resolution sleep()
. Simply set the first two parameters to 0 when calling the function, and set the timeout to be however many milliseconds you wish to delay your program. I use this when writing simple simulators at work, and it works well enough.
Just make sure your poll timeouts aren’t getting rounded or whatnot depending on the size of the jiffies set on in your operating system’s kernel.
For linux I think jiffies are 10ms by default and are always increments of 10ms, unless you apply some patch or something to give you better granularity.
So then poll() will most probably round up to the next 10ms (345ms delay becomes 350ms).
If it works well enough for you, then that’s good, but just keep that in mind that you might be off by up to < 10ms.
oh, and btw, there’s a bug in the handling of < and < for the preview/submit forms for this.
by Iluvitar on May 12 2006, 2:36 pm #
The 2nd < was supposed to be & lt; without the space . . .
by Iluvitar on May 12 2006, 2:37 pm #
That’s right Patrick; I’m not sure how you would code up a higher resolution timer that was cross platform. The ones I’ve seen involve using asembly to do this or that.
And it must be some textile issue that you can’t have a < touching anything.
by ramanan on May 12 2006, 2:48 pm #
Oh, and since poll takes a timeout of size int milliseconds, the max you can timeout with poll is 2147483647 (maybe -1 depending on your cpu’s, OS’s or programming language’s selection of MAX_INT), well rounded up to 2147483650ms (almost 25 days I think). If you needed to timeout longer than that with the accuracy of poll, then you’d probably be better off using select() which uses a timeout struct that contains both seconds and milliseconds in two separate long’s, giving you delay times greater than 68 years… but by that time I guess you’d probably be better off using something else.
by Iluvitar on May 12 2006, 2:54 pm #
Could anyone help in determining any command which uses very less
CPU resources than the sleep uses.
by charu on August 21 2007, 6:54 am #
Maybe, I don’t know, this just off the top of my head:
poll
.by ramanan on August 21 2007, 7:49 am #