Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sleep for a millisecond in Perl?

Tags:

sleep

perl

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

like image 227
ˈoʊ sɪks Avatar asked May 22 '09 08:05

ˈoʊ sɪks


2 Answers

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);
like image 95
Chris Lutz Avatar answered Nov 01 '22 21:11

Chris Lutz


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

like image 37
Greg Avatar answered Nov 01 '22 19:11

Greg