terminating a parfor loop early
Show older comments
Like lots of people before me, I'm looking for a way to get something like Break functionality in a parfor loop.
My code is an embarrasingly-parallel montecarlo code. I'm submitting runs with different input parameters for execution in a job queue. When I submit my job I specify a maximum runtime; if I accidentally submit a job that takes longer, my job terminates and I lose everything
I'd like to inside the parfor loop to check if I've exceed some specified runtime, and if so get out of the loop quickly so that the code can save to file the data it has already accumulated, rather than losing it all when the job is killed.
My plan was to do something below, so that if the loop takes longer than maxruntime, the loop will effectively be empty and we will quickly run through any remaining iterations.
My problem is that using datetime seems to be extremely slow.
Is there a better way to do what I want, or a faster way of checking time across different cores?
maxruntime=hours(4); %set maximum runtime to 4 hours
starttime=datetime; %save the time at which we start the parfor
parfor packets=1:N
if (datetime-starttime)<maxruntime
%the normal loop code goes in here
%arrays are accumulated
end
end
%code to write out the accumulated arrays from the parfor loop is here
Accepted Answer
More Answers (1)
Rik
on 2 Feb 2022
1 vote
I personally use the now function a lot. The number it returns is in days, so you will have to scale your max time to fractional days for the comparison.
2 Comments
David Spence
on 2 Feb 2022
Rik
on 2 Feb 2022
I doubt using toc with an input would be much faster, but you could try:
maxruntime=seconds(hours(4)); %set maximum runtime to 4 hours
starttime=tic; %save the time at which we start the parfor
parfor packets=1:N
if toc(starttime)<maxruntime
%the normal loop code goes in here
%arrays are accumulated
end
end
%code to write out the accumulated arrays from the parfor loop is here
It all depends on how much you're doing in the rest of your loop. If it is fast, then even a low-cost function will result in a drastic performance decrease.
I don't know many more strategies to query the system time. I believe using a mex doesn't beat calling now.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!