I’m doing some CLI scripting here and there and as I’m still on the way to implement it the right way using a framework like wpcli, wpshell or the like for my scripts I sometimes like to put a little progress bar in my scripts to see how things are going and how much longer the script might run. So this is what I do.
<?php
$time1 = time(); // set the start time
dosomethingnasty();
function dosomethingnasty() {
for( $i=0; $i < 300; $i++ ) {
progress( $i, 300 );
sleep( 1 );
}
}
/**
* Print simple progress bar.
*
* @access public
* @param int $processed amount of items processed
* @param int $max maximum amount of items to process
* @return void
*/
function progress( $processed, $max ) {
global $time1;
$progress = round( $processed / ( $max / 100 ), 2);
$progress_points = floor($progress/2);
$time_x=time();
$timediff = $time_x - $time1;
$estimation = round( ( ( ( 100 / $progress * $timediff ) - $timediff ) / 60 ), 2 );
echo str_pad( str_repeat( "#", $progress_points ), 52, " ", STR_PAD_RIGHT) . sprintf( "%.2f", $progress ) . str_pad( "% ( ". sprintf( "%.2f", $estimation ) . " min left )", 27, " ", STR_PAD_RIGHT). "\r" ;
}

December 14, 2011 


No comments yet... Be the first to leave a reply!