我正在尝试获取执行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
...
我很确定我误解了这样做的公式,如果有人可以提供帮助,我将非常感激。我不是在谈论发明人工智能,只需要一个如何获得剩余时间的例子。
答案 0 :(得分:1)
你必须递减$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.7s 第一次和9.6s 之后即可。为避免过大的变化,您应该应用平滑滤镜。
PS:当然你应该重命名/重新排列变量名称,因为没有人希望$total_urls
减少每次迭代......
编辑:
避免havy变化的一种可能性是,将最后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'");
}