如何计算执行时间(php指令';max_execution_time';?)


How to calculate execution time (php directive 'max_execution_time'? )

几天前写了一个php脚本,该脚本遍历我的所有音乐,读取每首歌的id3标签,并将这些标签插入到mysql数据库中。以下是上下文片段:

exec ( "find /songs -type f -iname '*mp3'", $song_path );
$number_of_songs = count($song_path);
for($i=0; $i<$number_of_songs; $i++){
    //read id3 tags
    //store id3 tags into database
}

我更改了apache2/php.ini中的php指令max_execution_time,以更好地了解该指令的作用。

当我设置max_execution_time = 10时,我的php脚本运行了大约45秒,成功读取了大约150首歌曲(数千首歌曲中的)的id3标签,并将这些标签插入到mysql数据库中,然后终止脚本并将以下内容输出到屏幕:

致命错误:/websites/中超过了10秒的最长执行时间/第1894行的public_html/GetID3()/GetID3/module.audio.mp3.php

从文档中,"最长执行时间不受系统调用、流操作等的影响"http://www.php.net/manual/en/info.configuration.php#ini.max-执行时间

  1. 我能从maximum_execution_time设置为10秒,脚本在终止之前总共运行了45秒?这样做吗平均45秒中,35秒用于做与php无关的事情读取id3标签、将数据插入mysql等活动,花费了10次做php相关的活动,比如迭代循环?

  2. 有没有办法计算执行时间并打印到屏幕?

编辑使用Dagon建议的计时器,我在循环结束时调用了getTime()函数,循环大约有100多次迭代。这是我的浏览器的输出:

0.1163秒

0.8142秒

1.1379秒

1.5555秒

76.7847秒

77.2008秒

77.6071秒

致命错误:/websites/中超过了10秒的最长执行时间/第505行的public_html/GetID3()/GetID3/module.audio.mp3.php

<!-- Paste this at the top of the page -->
<?php
   $mic_time = microtime();
   $mic_time = explode(" ",$mic_time);
   $mic_time = $mic_time[1] + $mic_time[0];
   $start_time = $mic_time;
?>
<!-- Write Your script(executable code) here  -->
enter code here
<!-- Paste  this code at the bottom of the page -->
<?php
   $mic_time = microtime();
   $mic_time = explode(" ",$mic_time);
   $mic_time = $mic_time[1] + $mic_time[0];
   $endtime = $mic_time;
   $total_execution_time = ($endtime - $start_time);
   echo "Total Executaion Time ".$total_execution_time." seconds";
?>

我不认为脚本实际运行时间超过10秒,你需要在中放入一个合适的计时器

<!-- put this at the top of the page -->
<?php
function getTime() {
    $timer = explode( ' ', microtime() );
    $timer = $timer[1] + $timer[0];
    return $timer;
}
$start = getTime();
?> 
<!-- put other code and html in here --> 
<!-- put this code at the bottom of the page -->
<?php
$end = getTime();
$time_took=  round($end - $start,4).' seconds';
echo $time_took;
?>

这种类型的脚本实际上应该在CLI环境中执行,而不是在web服务器执行的php进程中执行。根据关于PHP命令行环境与其他PHP SAPI:有何不同的手册文档

shell环境中的PHP往往用于更加多样化的与典型的基于Web的脚本相比非常长时间运行,最大执行时间设置为无限制

虽然它不能回答你的问题,但它确实解决了你的问题:)

似乎你不仅试图测量脚本持续时间,还试图限制它。在你的情况下,max_execution_time不是你想要的。

基本上,"最长执行时间不受系统调用、流操作等的影响"是正确的。如果需要限制实时脚本长度,则需要实现自己的时间度量。人们通常会为它编写一些基准类,毕竟这将有助于优化脚本,但简单的

$timer['start'] = time();
$timer['max_exec_time'] = 10; // seconds

启动时和

if (time() > $timer['start'] + $timer['max_exec_time'])
    break; // or exit; etc

在循环的末尾或其他任何您想要的地方都应该足够了。