Question

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?

Was it helpful?

Solution 2

use threads;

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

# rest of program..

OTHER TIPS

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

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.

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                                  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top