0
<?php
echo '<html><body>';
set_time_limit(1);
$i = 0;
while(++$i < 100000001){
        if($i % 100000 == 0){
                echo $i / 100000, "<br/>\n";
        }
}
echo "done.<br/>\n";

// will not echo 'done.'.
?>

The above code keeps echoing echo $i / 100000, "<br/>\n"; till 1 second and then stops the execution since I have used set_time_limit(1);

But I want it to echo only if the complete loop gets executed within 1 sec and else instead of echoing I want to pop up or display a message that says timeout or cannot perform execution in 1 sec.

Is it possible to achieve this somehow in PHP?

Mukul Kumar
  • 564
  • 1
  • 5
  • 24
  • I hope you want this: [Tracking the script execution time in PHP](https://stackoverflow.com/questions/535020/tracking-the-script-execution-time-in-php) – Alive to die - Anant Mar 16 '23 at 05:47
  • 1
    Its a sample code. In a real code, the situation is similar to this. @nice_dev – Mukul Kumar Mar 16 '23 at 05:59
  • 1
    You could try and catch the fatal error that occurs when the max execution time is reached, https://stackoverflow.com/a/11704803/1427878 – CBroe Mar 16 '23 at 07:59

1 Answers1

0

set_time_limit(1) is unsuitable for this task. Just check the runtime of the script with microtime.

$stop = microtime(true) + 1;
$i = 0;
while(microtime(true) < $stop){
        if(++$i % 1000000 == 0){
                echo $i / 1000000, "<br/>\n";
        }
}
echo "done.<br/>\n";

Output:

1
2
3
4
5
6
7
8
9
10
11
done.

Test on 3v4l.org

jspit
  • 7,276
  • 1
  • 9
  • 17