This repository has been archived by the owner on Jun 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
waitbarParfor.m
73 lines (54 loc) · 2.38 KB
/
waitbarParfor.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
function [triggerUpdateFcn] = waitbarParfor(totalLoops, varargin)
%waitbarParfor Waitbar implementation for parfor loops.
% [triggerUpdateFcn] = waitbarParfor(totalLoops) creates a waitbar for use in parfor loops. totalLoops indicates the number of loops until
% completion. Use the triggerUpdateFcn to increment the waitbar count. Make sure to call this function in the outer parfor loop.
% waitbarParfor(___, message) displays the specified message on the waitbar.
% waitbarParfor(___, Name, Value) accepts all Name-Value pairs for the waitbar function. Use the "Name" option to set the window title.
%
% Example
% nLoops = 100;
%
% updateWaitbar = waitbarParfor(nLoops, "Calculation in progress...");
% parfor loopCnt = 1:nLoops
% A = rand(5000);
% updateWaitbar(); %#ok<PFBNS>
% end
%
% Author: Girmi Schouten ([email protected]), 2019.
% Written in MATLAB 2019b, tested on Ubuntu 18.04 & Windows 10.
%% Parse input arguments
argParser = inputParser();
argParser.KeepUnmatched = true;
addRequired(argParser, "totalLoops", @isscalar);
defaultWaitbarMessage = "Please wait ...";
addOptional(argParser, "waitbarMessage", defaultWaitbarMessage, @(str) isstring(str) || ischar(str));
parse(argParser, totalLoops, varargin{:});
totalLoops = argParser.Results.totalLoops;
waitbarMessage = argParser.Results.waitbarMessage;
%% Initialize waitbar requirements
parellelDataQueue = parallel.pool.DataQueue;
afterEach(parellelDataQueue, @updateWaitbar);
waitbarHandle = waitbar(0, waitbarMessage);
% Pass unmatched parameters to the waitbar
if ~isempty(fieldnames(argParser.Unmatched))
waitbarOptions = namedargs2cell(argParser.Unmatched);
set(waitbarHandle, waitbarOptions{:});
end
triggerUpdateFcn = @updateProxy;
loopCnt = 1;
%% Helper functions
function updateWaitbar(~)
if ~isvalid(waitbarHandle)
warning("waitbarParfor:waitbarExpired", "The waitbar has expired, please create a new one.");
return;
elseif loopCnt == totalLoops
close(waitbarHandle);
return;
end
waitbar(loopCnt/totalLoops, waitbarHandle);
loopCnt = loopCnt + 1;
end
function updateProxy()
send(parellelDataQueue, []);
end
end