0
<?php
set_time_limit(4);
echo  ini_get('max_execution_time'); // give value as 4
while ($i<=10) 
{
    echo "i=$i ";
    sleep(1);
    $i++;
}

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

Expected behaviour: It should end its execution after 4 seconds.

Please explain ?

chicharito
  • 1,047
  • 3
  • 12
  • 41

2 Answers2

1

Which version you are using?

I used the version PHP Version 5.4.7 and I got the result

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

Also while setting the set_time_limit(), the duration of sleep() will be ignored in the execution time. The following illustrates:

<?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

Source From set_time_limit()

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
  • Actually, it is more likely that you are using Windows and topic starter Unix. The thing is, `set_time_limit` must affect only script execution time and NOT system calls, which is what `sleep()` does, but it is buggy under Windows and counts system calls as well. – Cthulhu Aug 08 '13 at 04:52
1

You should try this, just have a script that sleeps for more than your maximum execution time.

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

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

This is how you can get the computation time and system calls 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";
Mangesh Parte
  • 2,179
  • 1
  • 13
  • 16
  • Can i do something that i can use overall time rather than execution time ? – chicharito Aug 08 '13 at 05:48
  • Please explain in detail about what you want to do? – Mangesh Parte Aug 08 '13 at 05:51
  • I want script to end its execution as soon as a threshold is reached – chicharito Aug 08 '13 at 06:10
  • Note: The configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), the sleep() function, database queries, etc. is not included when determining the maximum time that the script has been running. – Mangesh Parte Aug 08 '13 at 06:31