perl - printing on screen periodically without sleep()

422 views Asked by At

I have been coding with perl and I am doing some calculations, which are taking some time in a long for loop... Size of the loop is given by the user.

So in every ten seconds or so, I want to print some info on screen, without using sleep function, because there are other things going on and I don't want to waste time on sleep function.

Any ideas?

4

There are 4 answers

0
mpapec On BEST ANSWER
use threads;

async {
  my $i = 0;
  LOOP: {
    print $i++, "\n";
    sleep 10;
    redo LOOP;
  }
};

# rest of program..
1
JRFerguson On

You could use Smart::Comments to produce a progress bar.

use Smart::Comments;
use Time::HiRes qw(usleep);
### process started
for my $n (0..1000000) { ### Initializing...  done
    usleep 5; #...simulate work...
}
### process ended
1;

Which would produce:

### process started
Initializing..............     done                                  
0
AudioBubble On

Usually it's not a problem. Because you have a progress of your job. Relying on this progress you can occasionally print something.

But if you want to print exactly every 10 seconds it's probably better to use another thread to print the progress to user every 10 seconds and sleep() function.

Also you could deal with clock directly i.e. keep startTime and calculate currentTime if their differenceInSeconds % 10 == 0 then print something.

1
Floris On

If you want to print something in a long loop after every five seconds, you can do something like this (pseudocode but you get the idea):

tLast = currentTime modulo interval

for (some long loop):
  tNow = currentTime modulo interval
  if tNow < tLast:
    print "something"
  tLast = tNow
  doSomethingElse

If the loop is quite tight and this would add too much overhead, do

for (some long loop):
  tNow = currentTime modulo interval
  if tNow < tLast:
    print "something"
  tLast = tNow
  for(some tight loop):
     doSomethingElse

Now the checking of the time happens "only every so often" - so no overhead for the tightest loop, only for the less-tight outer loop (this is in essence a combination of what I proposed in my first comment, and what I proposed in a later one).