【问题标题】:set_time_limit is not working as expected?set_time_limit 没有按预期工作?
【发布时间】:2013-08-09 16:39:31
【问题描述】:
<?php
set_time_limit(4);
echo  ini_get('max_execution_time'); // give value as 4
while ($i<=10) 
{
    echo "i=$i ";
    sleep(1);
    $i++;
}

输出:4i= i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9 i=10

预期行为:它应该在 4 秒后结束执行。

请解释一下?

【问题讨论】:

    标签: php php-5.2 php-5.4


    【解决方案1】:

    你应该试试这个,只要有一个休眠的脚本超过你的最大执行时间。

    sleep(ini_get('max_execution_time') + 10);
    

    阅读:Under Linux, sleeping time is ignored, but under Windows, it counts as execution time.

    这是获取计算时间和系统调用时间的方法。

    // Script start
    $rustart = getrusage();
    
    // Code ...
    
    // Script end
    function rutime($ru, $rus, $index) {
        return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
         -  ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
    }
    
    $ru = getrusage();
    echo "This process used " . rutime($ru, $rustart, "utime") .
        " ms for its computations\n";
    echo "It spent " . rutime($ru, $rustart, "stime") .
        " ms in system calls\n";
    

    【讨论】:

    • 我可以做一些我可以使用整体时间而不是执行时间的事情吗?
    • 请详细说明你想做什么?
    • 我希望脚本在达到阈值后立即结束执行
    • 注意:配置指令 max_execution_time 只影响脚本本身的执行时间。在确定脚本运行的最长时间时,不包括在脚本执行之外发生的活动所花费的任何时间,例如使用 system() 的系统调用、sleep() 函数、数据库查询等。跨度>
    【解决方案2】:

    您使用的是哪个版本?

    我用的版本是PHP Version 5.4.7,我得到了结果

    4i=0 i=1 i=2 i=3 i=4
    Fatal error: Maximum execution time of 4 seconds exceeded in .......
    

    同样在设置 set_time_limit() 时,sleep() 的持续时间将在执行时间中忽略强>。下图说明:

    <?php
        set_time_limit(20);
        while ($i<=10)
        {
           echo "i=$i ";
           sleep(100);
           $i++;
        }    
    ?>
    
    Output:
    i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9 i=10
    

    来自set_time_limit()

    【讨论】:

    • 实际上,您更有可能使用的是 Windows 和主题启动器 Unix。问题是,set_time_limit 必须只影响脚本执行时间而不影响系统调用,这是 sleep() 所做的,但它在 Windows 下存在错误,并且也计算系统调用。
    猜你喜欢
    • 1970-01-01
    • 2021-10-19
    • 2020-03-18
    • 2012-06-14
    • 2014-11-15
    • 1970-01-01
    • 2012-07-02
    • 2011-09-07
    • 2013-03-03
    相关资源
    最近更新 更多