PHP进展的结局未知

时间:2015-02-02 10:27:30

标签: php math optimization

我需要在结束时间未知的应用程序中显示一些进展。用户必须知道该进程仍在运行。我采取了一种方法,我总是采取一定比例的步骤,永远不会达到100%。我的代码确实有效但我想优化它。有没有办法用数学函数替换内部for循环?

$start = new DateTime();
$end = new DateTime('2999-01-01');

$total = $end->format('U') - $start->format('U');
while (true) {
    $secondsLeft = $end->format('U') - $start->format('U');

    $progress = 0;
    $amount = 100;
    $worked = 0;
    for ($i = 0; $i < $total - $secondsLeft; $i ++) {
        $worked = $amount / 100;
        $amount = $amount - $worked;
        $progress += $worked;
    }
    print('worked: ' . $worked . '  ');
    print('progress: ' . $progress . PHP_EOL);

    $start->modify('+1 seconds');
    sleep(1);
}

1 个答案:

答案 0 :(得分:-1)

类似的效果,它永远不会达到100%

$worked = 0;
$x = 100;
$z = 0;
while (true) {
    $y = $z; 
    $worked++;
    $z = $worked/($x+$worked); 
    echo $z-$y.";".$z."\n";    
    sleep(1);
}