views:

8879

answers:

5

How do I sleep for shorter than a second in Perl?

+13  A: 

Time::HiRes:

  use Time::HiRes;
  Time::HiRes::sleep(0.1); #.1 seconds
  Time::HiRes::usleep(1); # 1 microsecond.

http://perldoc.perl.org/Time/HiRes.html

Greg
a lousy 34 seconds :)
TML
usleep() sleeps for microseconds, not milliseconds.
Chris Lutz
oops. ta. fixed.
Greg
+5  A: 

Use Time::HiRes.

TML
+3  A: 

A quick googling on "perl high resolution timers" gave a reference to Time::HiRes. Maybe that it what you want.

JesperE
+25  A: 

From the Perldoc page on sleep:

For delays of finer granularity than one second, the Time::HiRes module (from CPAN, and starting from Perl 5.8 part of the standard distribution) provides usleep().

Actually, it provides usleep() (which sleeps in microseconds) and nanosleep() (which sleeps in nanoseconds). You may want usleep(), which should let you deal with easier numbers. 1 millisecond sleep (using each):

use strict;
use warnings;

use Time::HiRes qw(usleep nanosleep);

# 1 millisecond == 1000 microseconds
usleep(1000);
# 1 microsecond == 1000 nanoseconds
nanosleep(1000000);

If you don't want to (or can't) load a module to do this, you may also be able to use the built-in select() function:

# Sleep for 250 milliseconds
select(undef, undef, undef, 0.25);
Chris Lutz
Caveat: although you could nanosleep(1), many OSes have some minimum granularity; e.g. I believe it's 1 ms in Windows XP, so you'd still sleep for a whole 1000000 ns there.
Piskvor
The page on Time::HiRes says something like "if you need nanosleep(), you should reconsider whether or not Perl is the best tool for your job."
Chris Lutz
+8  A: 

From perlfaq8:


How can I sleep() or alarm() for under a second?

If you want finer granularity than the 1 second that the sleep() function provides, the easiest way is to use the select() function as documented in select in perlfunc. Try the Time::HiRes and the BSD::Itimer modules (available from CPAN, and starting from Perl 5.8 Time::HiRes is part of the standard distribution).

brian d foy