views:

59

answers:

3

I have a script which runs in a 'while' cycle. I need to determine for how long the script was running for and if it is over 10 seconds terminate it. The code I wrote returns weird decimal values (one second it might be '5.342...' and other it might be '903.322...'). Can someone tell me how can I achieve that?

$timer = microtime(false);
while(/*...*/)
{
   $currTime = microtime(false);
   $timeDiff = $currTime - $timer;
   $timeDiff *= 1000;

   if ($timeDiff > 10)
   {
      //...
   }
}
+2  A: 

You're tracking microseconds. If you want to see only the seconds, round it
up using round() or ceil().

You might also consider set_time_limit(), which controls how long the script is allowed to run for.

set_time_limit(10); // allow ten seconds for this script to finish

You can use register_shutdown_function() to handle any cleanup that is necessary if the script didn't finish in time.

Jonathan Sampson
Won't multiplying it by 1000 do it?
Nick Brooks
No, multiplying by 1000 won't necessarily ensure a non-fraction result: `3.29381 * 1000 = 3293.81`
Jonathan Sampson
The whole point is that I must not let this thing trigger an error. So I must make sure that the script terminates if it reaches 10 seconds.
Nick Brooks
Nick, you can use `register_shutdown_function()` to handle things if the script didn't finish in time.
Jonathan Sampson
+1  A: 
$timeDiff /= 1000;

1000 microseconds is a second, not the other way around

BlueRaja - Danny Pflughoeft
+1  A: 

I believe the argument should be true, see http://php.net/manual/en/function.microtime.php

Try:

$timer = microtime(true);
while(true)
{
   $currTime = microtime(true);
   $timeDiff = $currTime - $timer;

   if ($timeDiff > 10)
   {
      die();
   }
}
asgerhallas
It will not be accurate down to the milisecond though - only +/- a second.
asgerhallas