Fractional sleep

Submitted by gwolf on Mon, 06/19/2006 - 17:49
How cool is this? [code="ruby"] if pid=fork while true puts "#{Time.now.sec}: I'm the slow #{Process.pid}, parent of #{pid}" sleep 1 end else while true puts "#{Time.now.sec}: I'm the fast #{Process.pid}, child of #{Process.ppid}" sleep 1.0/3 end end [/code] What do I get?
18: I'm the fast 9900, child of 9899 18: I'm the slow 9899, parent of 9900 18: I'm the fast 9900, child of 9899 19: I'm the fast 9900, child of 9899 19: I'm the slow 9899, parent of 9900 19: I'm the fast 9900, child of 9899 19: I'm the fast 9900, child of 9899 20: I'm the fast 9900, child of 9899 20: I'm the slow 9899, parent of 9900 20: I'm the fast 9900, child of 9899 20: I'm the fast 9900, child of 9899
And for those of you not familiar with sleep(3), what is so cool about this? Simple: The prototype for sleep in almost any language is: [code="c"] #include unsigned int sleep(unsigned int seconds); [/code] (note the unsigned int part?) Even the Perl documentation clearly says, being compliant with the rest of the world:
For delays of finer granularity than one second, you may use Perl's "syscall" interface to access setitimer(2) if your system supports it, or else see "select" above. The Time::HiRes module (from CPAN, and starting from Perl 5.8 part of the standard distribution) may also help.
But... Well, in this case I just loved the Ruby way: If it does not hurt to cause surprises, then don't cause them! Keep a simple, portable definition, that will work with seconds or with fractions! Why not?
( categories: )
Seo Sanghyeon's picture

Re: Fractional sleep

FWIW, Python does fractional sleep too. pydoc time.sleep.
bartman's picture

Re: Fractional sleep, in bash

meson:~# time sleep 1 real 0m1.002s user 0m0.000s sys 0m0.001s meson:~# time sleep 0.1 real 0m0.103s user 0m0.001s sys 0m0.000s