Perl Cookbook

Perl CookbookSearch this book
Previous: 3.9. High-Resolution TimersChapter 3
Dates and Times
Next: 3.11. Program: hopdelta
 

3.10. Short Sleeps

Problem

You need to sleep for less than a second.

Solution

Use the select() function, if your system supports it:

select(undef, undef, undef, $time_to_sleep);

Some systems don't support a four-argument select. The Time::HiRes module provides a sleep function that takes a floating point number of seconds:

use Time::HiRes qw(sleep);
sleep($time_to_sleep);

Discussion

Here's an example of select. It's a simpler version of the program in Recipe 1.5. Think of it as your very own 300-baud terminal.

while (<>) {
    select(undef, undef, undef, 0.25);
    print;
}

Using Time::HiRes, we'd write it as:

use Time::HiRes qw(sleep);
while (<>) {
    sleep(0.25);
    print;
}

See Also

The documentation for the CPAN modules Time::HiRes and BenchMark; the sleep and select functions in perlfunc (1) and Chapter 3 of Programming Perl; we use the select function for short sleeps in the slowcat program in Recipe 1.5


Previous: 3.9. High-Resolution TimersPerl CookbookNext: 3.11. Program: hopdelta
3.9. High-Resolution TimersBook Index3.11. Program: hopdelta