How to sleep less then 1 second

T

tower.grv

Hello.
I want my Perl script execute some code in the begining of each
second.

I have code
----------------------------------------------------
#!/usr/bin/perl -w
my $thistime=time();
while(1){

while(time()-$thistime<1) {my $a=1;}

$thistime=time();
print $thistime."\n";
#some more code

}
----------------------------------------------------
This code works but it takes a lot of CPU resources.
sleep(1) is not good for me. Usually it is needed to sleep less then
second.

Is it possible to replace line
while(time()-$thistime<1) {my $a=1;}
with better code?
 
J

Jens Thoms Toerring

I want my Perl script execute some code in the begining of each
second.
I have code
while(time()-$thistime<1) {my $a=1;}
$thistime=time();
print $thistime."\n";
#some more code
Is it possible to replace line
while(time()-$thistime<1) {my $a=1;}
with better code?

Yes. Use e.g.

select( undef, undef, undef, $delay );

where $delay is the time (in seconds but with sub-second resolution)
you want your process to sleep.
Regards, Jens
 
P

Peter J. Holzer

This code works but it takes a lot of CPU resources.
sleep(1) is not good for me. Usually it is needed to sleep less then
second.

See Time::HiRes

hp
 
S

smallpond

Hello.
I want my Perl script execute some code in the begining of each
second.

I have code
----------------------------------------------------
#!/usr/bin/perl -w
my $thistime=time();
while(1){

while(time()-$thistime<1) {my $a=1;}

$thistime=time();
print $thistime."\n";
#some more code

}

----------------------------------------------------
This code works but it takes a lot of CPU resources.
sleep(1) is not good for me. Usually it is needed to sleep less then
second.

Is it possible to replace line
while(time()-$thistime<1) {my $a=1;}
with better code?

TMTOWTDI
Tk has a millisecond timer.

#!/usr/bin/perl
use warnings;
use strict;

use Tk;
my $w = MainWindow->new();
my $times = 10;

sub do_stuff {
print "doing $times\n";
$w->destroy if $times-- == 0;
}

$w->repeat(1000, \&do_stuff);
MainLoop();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,045
Members
48,769
Latest member
Clifft

Latest Threads

Top