Search

Search this site:

Fractional sleep

How cool is this? 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 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: #include unsigned int sleep(unsigned int seconds); (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?

Comments

bartman 2006-06-19 17:31:05

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


Seo Sanghyeon 2006-06-19 16:35:24

Re: Fractional sleep

FWIW, Python does fractional sleep too. pydoc time.sleep.

Categories