Why do witches burn?

Because they’re made of wood, like bridges, and so float on water, like churches, very small rocks, gravy, and a duck.

Displaying a progress bar

Le mars 1st, 2009

Ok, it’s not really a bar. Draw something, being careful of the width of your command-line terminal, is tricky. But, you’ll get the display of the percentage of progress of the script and the time that is probably remaining.

Example. You have a script doing 20,000 times about the same thing. You want to know how things are going.
Most of you will have done, at the end of the loop, the following code:

echo "Progress: ".(100*($cpt++)/20000)." % \n";

Well, we do the same thing, but better.

//! greate function writing progress and remaining time
/** At first call, give "max" which is the number of time the function will be called, after */
function write_progress($max=null) {
    static $cpt;
    if ($max!==null) {
        $cpt = array(
                'debut' => time(),
                'cpt' => 0,
                'max' => (int) $max,
                );
    }
    if (!$cpt) die("\n[write_progress] Bad parameters.\n");
 
    $cpt['cpt']++;
    $elapsed = time()-$cpt['debut'];
    $restant = round($cpt['max']*$elapsed/$cpt['cpt']) - $elapsed;
    $pourcent = round(100*$cpt['cpt']/$cpt['max']);
    echo "  -+-  $pourcent%  -  Temps so far: ".
        write_temps($elapsed)."  -  Temps remaining: ".write_temps($restant)."     \r";
}

This function use write_temps(), the second function given on this link.

Usage:

$max = number_of_elements_to_check_or_number_of_lines_of_file();
write_avancement($max); // this does not output anything
while ( loop_on_each_element_or_line ) {
    do_many_things();
    write_avancement();
}
echo "\n"; // better if you don't want the prompt being in the "bar" display

Leave a Reply