Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: printing a running count

by liverpole (Monsignor)
on Sep 16, 2005 at 12:14 UTC ( [id://492589]=note: print w/replies, xml ) Need Help??


in reply to printing a running count

You could use a trick I often use, to display a running count, but on the same line:
#!/usr/bin/perl -w + # Strict use strict; use warnings; + + # User-defined my $interval = 10; + + # Main program $| = 1; # Flush STDOUT my $i; my $total = 10_000; + for ($i = 0; $i < $total; $i++) { (0 == ($i % $interval)) and printf " Progress %5d/%5d\e[K\r", $i, +$total; # Call your code here &my_subroutine(); } printf " Progress %5d/%5d\e[K\n", $i, $total; + + # Subroutines sub my_subroutine() { # For test purposes, sleep for a random interval of milliseconds my $nmilli = int(rand(1100) / 1000); select(undef, undef, undef, $nmilli); }
Every time the index variable $i reaches a multiple of $interval (which is 10 in the above program), the line:
(0 == ($i % $interval)) and printf " Progress %5d/%5d\e[K\r", $i, +$total;
causes a count to be displayed, along with the total.  The escape sequence "\e[K" erases to the end of the line, and the carriage-return "\r" repositions the cursor at the beginning of the line (which is why I recommend pussing the extra space before the word "Progress").  At the end of the loop, don't forget to rewrite the progress, but this time with "\n" to finally go to a new line.

You can change the output to your liking; from displaying only the count (with no label) to displaying the percentage complete (eg. printf " Progress %7.3f%%", 100 * $i / $total;"), etc.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://492589]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-03-29 02:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found