获取php脚本执行的剩余时间


Get remaining time execution of php script

我正在尝试获得执行php脚本的当前剩余时间。

我试着:

$urls1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$total_urls = count($urls1);
foreach ($urls1 as $url) {
  $start_time = microtime(true);
  // here I do some things
  $time_end = microtime(true);
  $execution_time = $time_end - $start_time;
  $current_urls_remaining = $total_urls - 1;
  $total_time = $current_urls_remaining * floatval($execution_time);
  $timeleft = $total_time - floatval($execution_time);
  $db->query("UPDATE sessions SET timeleft = '$timeleft'");
}

//问题是它是用随机数更新的

预期输出

 Iteration 1 - Remaining approximate time let's say 5 second
 Iteration 2 - Remaining approximate time 4 seconds
 Iteration 3 - Remaining approximate time 3.5 seconds
 ...

我很确定我错了这样做的公式,如果有人能帮助一个例子将不胜感激。我不是在谈论发明人工智能,只是需要一个如何获得剩余时间的例子。

你必须减少$total_urls,然后它应该工作,我认为。

例如:

$urls1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$total_urls = count($urls1);
foreach ($urls1 as $url) {
  $start_time = microtime(true);
  // here I do some things
  $time_end = microtime(true);
  $execution_time = $time_end - $start_time;
  $current_urls_remaining = --$total_urls;
  $total_time = $current_urls_remaining * floatval($execution_time);
  $timeleft = $total_time; //former: $timeleft = $total_time - floatval($execution_time);
  $db->query("UPDATE sessions SET timeleft = '$timeleft'");
}

你永远不会得到一个准确的值,因为一次执行可能持续0.3秒,下一次可能持续1.2秒,这将导致大约2.7秒首先和9.6秒之后的持续时间。为了避免太大的变化,你应该使用平滑过滤器。

PS:当然你应该重命名/重新排列变量名,因为没有人会期望$total_urls每次迭代都递减…

编辑:

避免剧烈变化的一种可能性是,取最后4个值的平均值作为估计持续时间:

$urls1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$total_urls = count($urls1);
$sf_last_values = array();
foreach ($urls1 as $url) {
  $start_time = microtime(true);
  // here I do some things
  $time_end = microtime(true);
  $execution_time = $time_end - $start_time;
  $sf_last_values[] = $execution_time;
  if(count($sf_last_values) > 4)
    array_shift($sf_last_values);
  $smoothened_execution_time = array_sum($sf_last_values) / count($sf_last_values);
  $current_urls_remaining = --$total_urls;
  $total_time = $current_urls_remaining * floatval($smoothened_execution_time);
  $timeleft = $total_time; //former: $timeleft = $total_time - floatval($execution_time);
  $db->query("UPDATE sessions SET timeleft = '$timeleft'");
}