(par)for k=1:N end; select for or parfor loop without code replication
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
I like to use for-loop or parfor-loop with function input flag. One way to do that is using if-else with code replication. I wonder is there a cleverer way?
% solution based on code replication
function foo(parflag)
if parflg==true
parfor k=1:3
% processing codes
end
else
for k=1:3
% copy of processing codes
end
end
end
%% wondering how to make this idea work?
function hoo(parflag)
if parflag==true
forString = str2func('parfor')
else
forString = str2func('for')
end
forString k=1:3
% processing codes
end
end
채택된 답변
You can avoid replicating the loop code as follows.
numWorkers={}; % or whatever
if ~parflag
numWorkers={0};
end
parfor (k=1:3, numWorkers{:})
% processing codes
end
Be mindful, though, that parfor loops have stronger requirements on the code structure, and you would be limiting yourself to that, even when running serially.
댓글 수: 13
Bruno Luong
2023년 8월 23일
편집: Bruno Luong
2023년 8월 23일
does it start the parallel pool, etc... even for simple for-loop?
No, it doesn't.
That would work. Parfor with zero worket would be a bit slower than for loop, but it won't affect much. I think this is an acceptable answer.
Parfor with zero worket would be a bit slower than for loop
Same question for to parfeval? Can I set something for mypool so that it runs without parallel pool?
mypool = backgroundPool;
Future(1) = parfeval(mypool,@(x)sin(x), 1, pi);
% ...
Same question for to parfeval
That I don't know, but it's less of a problem, because parfeval has a functional form, unlike parfor. You could therefore make a wrapper for parfeval that will handle the pool-free case.
To add on to Matt's great comments, you can pass an empty pool flag to parfeval and it will run in serial in the background. Here is an example of what I mean:
delete(gcp); % Ensure no pool is open
p = gcp('nocreate');
% No pool exists, so p is empty
for i = 1:3
f(i) = parfeval(p,@pause, 0);
end
p = parpool("Threads");
% p exists and will be used to run parfeval
for i = 1:3
f(i) = parfeval(p,@pause, 0);
end
In short, you can pass the pool object over to parfeval and if it is empty, it won't be used.
Bruno Luong
2023년 8월 23일
편집: Bruno Luong
2023년 8월 23일
@Sam Marshalik great thank you !
I just tested it in my real project and it seems working well. Now I have one base code for both parallel and non-parallel calculation.
This is also a convenient way to debug the parallel code, just switch to empty pool and voilà.
% why using cell?
numWorkers = {};
if ~parflag
numWorkers = {0};
end
% this is simpler, isn't it?
if ~parflag
numWorkers = 0;
end
% Both of them work.
Bruno Luong
2023년 8월 24일
편집: Bruno Luong
2023년 8월 24일
Good question, further more passing cell is not documented as from parfor doc
"parfor (loopvar = initval:endval, M); statements; end executes statements in a loop using a maximum of M workers or threads, where M is a nonnegative integer."
Actually, if we adpot numWorkers as a scalar number, we don't need if-else to make the selection.
function foo(x, numWorkers)
parfor (1:length(x), numWorkers)
% processing codes
end
end
foo(x, 0) % for loop
foo(x, 3) % parfor loop using 3 workers
But then you have to manually set numWorkers
Yes, that flexibility works for me. For example, when I am not doing anything but programming Matlab, I can set it to the maximum number of workers my compouter has. But when I heavily multitask, I can set numWorkers, say, 2 or 3, and let other cores to work on non-Matlab tasks. (I guess that's how my Mac would work.)
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Parallel for-Loops (parfor)에 대해 자세히 알아보기
참고 항목
웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
