Make a function time out in a parfor loop
古いコメントを表示
This is not a question but rather an answer as I found no information on this topic anywhere but it took some time work out how to do it and I thought other people might have the same problem.
Essentially, I want to execute some code within a parfor loop but want to allow a maximum amount of time to do this. If the code hasn't finished running by then, I want to skip that iteration of the parfor loop. This proved a bit more tricky when done inside a parfor loop. The following code works for me under R2023b.
It is essential that you call parfeval with 'backgroundPool' in this case (else it runs it serial) and the desired behaviour is lost!
timeout = 5;
parfor a = 1:10
tic
F = parfeval(backgroundPool,@testfunction,3,a,b);
while 1
if toc > timeout && ~isequal(F.State, "finished")
fprintf('Interrupted after %0.2f seconds\n', toc)
cancel(F)
break
elseif isequal(F.State, "finished")
fprintf("Finished in time - %0.2f seconds\n", toc)
break
end
end
end
where testfunction is the following function with a random pause of maximum 10 seconds:
function [c, d, e] = testfunction(a, b)
c = a+b;
d = a-b;
e = a*b;
duration = rand(1)*10; % Set a random pause time of between 0 and 10 seconds
pause(duration);
end
1 件のコメント
Walter Roberson
2025 年 7 月 29 日
Note that in order for this to work, the regular parfor has to be the process pool while the parfeval is the background pool.
If the regular parfor is in the background pool, then there is the possibility that all of the available background pools are in use and so there would be no slots available to run the parfeval(), so it would remain queued until canceled.
... Though it is not really clear from the documentation whether a background pool thread is able to call parfeval...
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Profile and Improve Performance についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!