Continue while loop after a certain time
Moderator: General Moderators
Continue while loop after a certain time
I've got a while loop that performs a lot of calculations.
If the calculations take more than (say) 2 seconds, I want the loop to give up and move on to the next item (ie. continue).
Is this possible?
If the calculations take more than (say) 2 seconds, I want the loop to give up and move on to the next item (ie. continue).
Is this possible?
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
- aerodromoi
- Forum Contributor
- Posts: 230
- Joined: Sun May 07, 2006 5:21 am
Re: Continue while loop after a certain time
How about using microtime to define a break statement?Grim... wrote:I've got a while loop that performs a lot of calculations.
If the calculations take more than (say) 2 seconds, I want the loop to give up and move on to the next item (ie. continue).
Is this possible?
- aerodromoi
- Forum Contributor
- Posts: 230
- Joined: Sun May 07, 2006 5:21 am
-
Robert Plank
- Forum Contributor
- Posts: 110
- Joined: Sun Dec 26, 2004 9:04 pm
- Contact:
If you're on unix look at these functions: http://php.net/pcntrl
Hopefully you know how to do multithreaded programming. Have a child process for each calculation. If the script finds out it's a child, set the timeout to 2. Then the mother process loops through and cleans up the zombies if they're dead. I don't know how you would share memory, I you might have to use a database for these guys to store their calculations, or maybe if static variables will carry over, I don't know. You'll have to mess around.
Hopefully you know how to do multithreaded programming. Have a child process for each calculation. If the script finds out it's a child, set the timeout to 2. Then the mother process loops through and cleans up the zombies if they're dead. I don't know how you would share memory, I you might have to use a database for these guys to store their calculations, or maybe if static variables will carry over, I don't know. You'll have to mess around.
If you are worried about getting stuck in a loop just set up an iteration counter.
Code: Select all
if(++$i === 1000) break;Why not something like...
Code: Select all
function MicroTimeFloat() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$Start = MicroTimeFloat();
while (1 < 2) {
if (($Start - MicrotimeFloat()) > 2) {
break;
}
// more code here
}