ˈoʊ sɪks
ˈoʊ sɪks

Reputation: 927

How do I sleep for a millisecond in Perl?

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

Upvotes: 88

Views: 129926

Answers (7)

Otheus
Otheus

Reputation: 585

For 1-liner on the CLI (for systems that don't have GNU's sleep:

perl -MTime::HiRes=usleep -e 'usleep(1000000);';

will sleep 1s. You can verify this by prefixing time to the command. So to convert from microseconds to milliseconds, multiply your expected milliseconds by 1000.

~ otheus$ time perl -MTime::HiRes=usleep -e 'usleep(1000000);';

real  0m1.032s
user  0m0.011s
sys   0m0.010s
~ otheus$ time perl -MTime::HiRes=usleep -e 'usleep(500000);';

real  0m0.547s
user  0m0.010s
sys   0m0.026s

Upvotes: 0

Tim Tian
Tim Tian

Reputation: 135

system "sleep 0.1";

does the trick.

Upvotes: 2

Chris Lutz
Chris Lutz

Reputation: 75419

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);

Upvotes: 125

brian d foy
brian d foy

Reputation: 132832

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).

Upvotes: 15

Greg
Greg

Reputation: 2179

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

Upvotes: 40

JesperE
JesperE

Reputation: 64414

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

Upvotes: 5

TML
TML

Reputation: 12966

Use Time::HiRes.

Upvotes: 7

Related Questions