PHP Logo

The other day I wrote a script that batched processed new records that took several seconds to process (each one could created hundreds of rows in a database and had to be compared against all other previous records). I really wanted to know how many records were left and how much more time it was going to take (so I can plan accordingly). Below is a modified version of the script so you can adapt it for your own uses.

<?php
function formatMinuteSeconds($value)
{
    $minutes = floor($value/60);
    $seconds = $value % 60;
    return sprintf('%d:%02d', $minutes, $seconds);
}

// create some data
$input = array();
for ($i = 0; $i<10; $i++) {
    $input[] = array();
}

$totalLines = count($input);
$startTime = microtime(true);
for ($current = 0; $current < $totalLines;) {
    $row = $totalLines[$current];

    // this is here to simulate the slow process
    sleep(10);

    // this is here so all the calculations are correct
    // and there isn't a division by zero
    $current++;

    $timeTaken = microtime(true) - $startTime;
    echo "Time Taken: ", formatMinuteSeconds($timeTaken);

    $linesLeft = $totalLines - $current;
    $timeLeft = ($timeTaken / $current) * $linesLeft;
    echo " Time Left: ", formatMinuteSeconds($timeLeft);
    echo " (", round($current/$totalLines * 100), "%)", PHP_EOL;
}

Output:

Time Taken: 0:10 Time Left: 1:30 (10%)
Time Taken: 0:20 Time Left: 1:20 (20%)
Time Taken: 0:30 Time Left: 1:10 (30%)
Time Taken: 0:40 Time Left: 1:00 (40%)
Time Taken: 0:50 Time Left: 0:50 (50%)
Time Taken: 1:00 Time Left: 0:40 (60%)
Time Taken: 1:10 Time Left: 0:30 (70%)
Time Taken: 1:20 Time Left: 0:20 (80%)
Time Taken: 1:30 Time Left: 0:10 (90%)
Time Taken: 1:40 Time Left: 0:00 (100%)