rbmatlab  1.16.09
 All Classes Namespaces Files Functions Variables Modules Pages
parfor_progress.m
Go to the documentation of this file.
1 function percent = parfor_progress(N)
2 %PARFOR_PROGRESS Progress monitor (progress bar) that works with parfor.
3 % PARFOR_PROGRESS works by creating a file called parfor_progress.txt in
4 % your working directory, and then keeping track of the parfor loop's
5 % progress within that file. This workaround is necessary because parfor
6 % workers cannot communicate with one another so there is no simple way
7 % to know which iterations have finished and which haven't.
8 %
9 % PARFOR_PROGRESS(N) initializes the progress monitor for a set of N
10 % upcoming calculations.
11 %
12 % PARFOR_PROGRESS updates the progress inside your parfor loop and
13 % displays an updated progress bar.
14 %
15 % PARFOR_PROGRESS(0) deletes parfor_progress.txt and finalizes progress
16 % bar.
17 %
18 % To suppress output from any of these functions, just ask for a return
19 % variable from the function calls, like PERCENT = PARFOR_PROGRESS which
20 % returns the percentage of completion.
21 %
22 % Example:
23 %
24 % N = 100;
25 % parfor_progress(N);
26 % parfor i=1:N
27 % pause(rand); % Replace with real code
29 % end
30 % parfor_progress(0);
31 %
32 % See also PARFOR.
33 
34 % By Jeremy Scheff - jdscheff@gmail.com - http://www.jeremyscheff.com/
35 
36 error(nargchk(0, 1, nargin, 'struct'));
37 
38 if nargin < 1
39  N = -1;
40 end
41 
42 percent = 0;
43 w = 50; % Width of progress bar
44 
45 if N > 0
46  f = fopen('parfor_progress.txt', 'w');
47  if f<0
48  error('Do you have write permissions for %s?', pwd);
49  end
50  fprintf(f, '%d\n', N); % Save N at the top of progress.txt
51  fclose(f);
52 
53  if nargout == 0
54  disp([' 0%[>', repmat(' ', 1, w), ']']);
55  end
56 elseif N == 0
57  delete('parfor_progress.txt');
58  percent = 100;
59 
60  if nargout == 0
61  disp([repmat(char(8), 1, (w+9)), char(10), '100%[', repmat('=', 1, w+1), ']']);
62  end
63 else
64  if ~exist('parfor_progress.txt', 'file')
65  error('parfor_progress.txt not found. Run PARFOR_PROGRESS(N) before PARFOR_PROGRESS to initialize parfor_progress.txt.');
66  end
67 
68  f = fopen('parfor_progress.txt', 'a');
69  fprintf(f, '1\n');
70  fclose(f);
71 
72  f = fopen('parfor_progress.txt', 'r');
73  progress = fscanf(f, '%d');
74  fclose(f);
75  percent = (length(progress)-1)/progress(1)*100;
76 
77  if nargout == 0
78  perc = sprintf('%3.0f%%', percent); % 4 characters wide, percentage
79  disp([repmat(char(8), 1, (w+9)), char(10), perc, '[', repmat('=', 1, round(percent*w/100)), '>', repmat(' ', 1, w - round(percent*w/100)), ']']);
80  end
81 end
function percent = parfor_progress(N)
PARFOR_PROGRESS Progress monitor (progress bar) that works with parfor. PARFOR_PROGRESS works by crea...