5798
|
1 ## Copyright (C) 2000-2006 Paul Kienzle |
5589
|
2 ## |
|
3 ## This program is free software; you can redistribute it and/or modify |
|
4 ## it under the terms of the GNU General Public License as published by |
|
5 ## the Free Software Foundation; either version 2 of the License, or |
|
6 ## (at your option) any later version. |
|
7 ## |
|
8 ## This program is distributed in the hope that it will be useful, |
|
9 ## but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
11 ## GNU General Public License for more details. |
|
12 ## |
|
13 ## You should have received a copy of the GNU General Public License |
|
14 ## along with this program; if not, write to the Free Software |
|
15 ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
|
16 ## 02110-1301 USA |
|
17 |
|
18 ## -*- texinfo -*- |
5798
|
19 ## @deftypefn {Function File} {} speed (@var{f}, @var{init}, @var{max_n}, @var{f2}, @var{tol}) |
|
20 ## @deftypefnx {Function File} {[@var{order}, @var{n}, @var{T_f}, @var{T_f2}] =} speed (@dots{}) |
5589
|
21 ## |
|
22 ## Determine the execution time of an expression for various @var{n}. |
|
23 ## The @var{n} are log-spaced from 1 to @var{max_n}. For each @var{n}, |
|
24 ## an initialization expression is computed to create whatever data |
5798
|
25 ## are needed for the test. If a second expression is given, the |
|
26 ## execution times of the two expressions will be compared. Called |
|
27 ## without output arguments the results are presented graphically. |
5589
|
28 ## |
|
29 ## @table @code |
|
30 ## @item @var{f} |
|
31 ## The expression to evaluate. |
|
32 ## |
|
33 ## @item @var{max_n} |
5798
|
34 ## The maximum test length to run. Default value is 100. Alternatively, |
|
35 ## use @code{[min_n,max_n]} or for complete control, @code{[n1,n2,@dots{},nk]}. |
5589
|
36 ## |
|
37 ## @item @var{init} |
|
38 ## Initialization expression for function argument values. Use @var{k} |
|
39 ## for the test number and @var{n} for the size of the test. This should |
|
40 ## compute values for all variables listed in args. Note that init will |
|
41 ## be evaluated first for k=0, so things which are constant throughout |
|
42 ## the test can be computed then. The default value is @code{@var{x} = |
|
43 ## randn (@var{n}, 1);}. |
|
44 ## |
|
45 ## @item @var{f2} |
|
46 ## An alternative expression to evaluate, so the speed of the two |
|
47 ## can be compared. Default is @code{[]}. |
|
48 ## |
|
49 ## @item @var{tol} |
|
50 ## If @var{tol} is @code{Inf}, then no comparison will be made between the |
|
51 ## results of expression @var{f} and expression @var{f2}. Otherwise, |
|
52 ## expression @var{f} should produce a value @var{v} and expression @var{f2} |
|
53 ## should produce a value @var{v2}, and these shall be compared using |
5798
|
54 ## @code{assert(@var{v},@var{v2},@var{tol})}. The default is |
5589
|
55 ## @code{eps}. |
|
56 ## |
5798
|
57 ## @item @var{order} |
|
58 ## The time complexity of the expression @code{O(a n^p)}. This |
|
59 ## is a structure with fields @code{a} and @code{p}. |
5589
|
60 ## |
5798
|
61 ## @item @var{n} |
|
62 ## The values @var{n} for which the expression was calculated and the |
|
63 ## the execution time was greater than zero. |
5589
|
64 ## |
5798
|
65 ## @item @var{T_f} |
|
66 ## The nonzero execution times recorded for the expression @var{f} in seconds. |
|
67 ## |
|
68 ## @item @var{T_f2} |
|
69 ## The nonzero execution times recorded for the expression @var{f2} in seconds. |
|
70 ## If it is needed, the mean time ratio is just @code{mean(T_f./T_f2)}. |
|
71 ## |
5589
|
72 ## @end table |
|
73 ## |
5798
|
74 ## The slope of the execution time graph shows the approximate |
|
75 ## power of the asymptotic running time @code{O(n^p)}. This |
|
76 ## power is plotted for the region over which it is approximated |
|
77 ## (the latter half of the graph). The estimated power is not |
|
78 ## very accurate, but should be sufficient to determine the |
|
79 ## general order of your algorithm. It should indicate if for |
|
80 ## example your implementation is unexpectedly @code{O(n^2)} |
|
81 ## rather than @code{O(n)} because it extends a vector each |
|
82 ## time through the loop rather than preallocating one which is |
|
83 ## big enough. For example, in the current version of Octave, |
|
84 ## the following is not the expected @code{O(n)}: |
5589
|
85 ## |
5798
|
86 ## @example |
|
87 ## speed("for i=1:n,y@{i@}=x(i); end", "", [1000,10000]) |
|
88 ## @end example |
|
89 ## |
|
90 ## but it is if you preallocate the cell array @code{y}: |
5589
|
91 ## |
|
92 ## @example |
5798
|
93 ## speed("for i=1:n,y@{i@}=x(i);end", ... |
|
94 ## "x=rand(n,1);y=cell(size(x));", [1000,10000]) |
|
95 ## @end example |
|
96 ## |
|
97 ## An attempt is made to approximate the cost of the individual |
|
98 ## operations, but it is wildly inaccurate. You can improve the |
|
99 ## stability somewhat by doing more work for each @code{n}. For |
|
100 ## example: |
|
101 ## |
|
102 ## @example |
|
103 ## speed("airy(x)", "x=rand(n,10)", [10000,100000]) |
5589
|
104 ## @end example |
|
105 ## |
5798
|
106 ## When comparing a new and original expression, the line on the |
|
107 ## speedup ratio graph should be larger than 1 if the new expression |
|
108 ## is faster. Better algorithms have a shallow slope. Generally, |
|
109 ## vectorizing an algorithm will not change the slope of the execution |
|
110 ## time graph, but it will shift it relative to the original. For |
|
111 ## example: |
|
112 ## |
|
113 ## @example |
|
114 ## speed("v=sum(x)", "", [10000,100000], ... |
|
115 ## "v=0;for i=1:length(x),v+=x(i);end") |
|
116 ## @end example |
|
117 ## |
5589
|
118 ## A more complex example, if you had an original version of @code{xcorr} |
|
119 ## using for loops and another version using an FFT, you could compare the |
|
120 ## run speed for various lags as follows, or for a fixed lag with varying |
|
121 ## vector lengths as follows: |
|
122 ## |
|
123 ## @example |
|
124 ## speed("v=xcorr(x,n)", "x=rand(128,1);", 100, ... |
|
125 ## "v2=xcorr_orig(x,n)", 100*eps,'rel') |
|
126 ## speed("v=xcorr(x,15)", "x=rand(20+n,1);", 100, ... |
|
127 ## "v2=xcorr_orig(x,n)", 100*eps,'rel') |
|
128 ## @end example |
|
129 ## |
|
130 ## Assuming one of the two versions is in @var{xcorr_orig}, this would |
|
131 ## would compare their speed and their output values. Note that the |
|
132 ## FFT version is not exact, so we specify an acceptable tolerance on |
|
133 ## the comparison @code{100*eps}, and the errors should be computed |
|
134 ## relatively, as @code{abs((@var{x} - @var{y})./@var{y})} rather than |
|
135 ## absolutely as @code{abs(@var{x} - @var{y})}. |
|
136 ## |
|
137 ## Type @code{example('speed')} to see some real examples. Note for |
|
138 ## obscure reasons, you can't run examples 1 and 2 directly using |
|
139 ## @code{demo('speed')}. Instead use, @code{eval(example('speed',1))} |
|
140 ## and @code{eval(example('speed',2))}. |
|
141 ## @end deftypefn |
|
142 |
|
143 ## TODO: consider two dimensional speedup surfaces for functions like kron. |
5798
|
144 function [__order, __test_n, __tnew, __torig] ... |
|
145 = speed (__f1, __init, __max_n, __f2, __tol) |
5589
|
146 if nargin < 1 || nargin > 6, |
6046
|
147 print_usage (); |
5589
|
148 endif |
|
149 if nargin < 2 || isempty(__init), |
|
150 __init = "x = randn(n, 1);"; |
|
151 endif |
|
152 if nargin < 3 || isempty(__max_n), __max_n = 100; endif |
|
153 if nargin < 4, __f2 = []; endif |
|
154 if nargin < 5 || isempty(__tol), __tol = eps; endif |
5798
|
155 |
|
156 __numtests = 15; |
5589
|
157 |
5798
|
158 ## Let user specify range of n |
|
159 if isscalar(__max_n) |
|
160 __min_n = 1; |
|
161 assert(__max_n > __min_n); |
|
162 __test_n = logspace(0,log10(__max_n),__numtests); |
|
163 elseif length(__max_n) == 2 |
|
164 __min_n = __max_n(1); |
|
165 __max_n = __max_n(2); |
|
166 assert(__min_n >= 1); |
|
167 __test_n = logspace(log10(__min_n),log10(__max_n),__numtests); |
|
168 else |
|
169 __test_n = __max_n; |
|
170 endif |
|
171 __test_n = unique(round(__test_n)); # Force n to be an integer |
|
172 assert(__test_n >= 1); |
5589
|
173 |
|
174 __torig = __tnew = zeros (size(__test_n)) ; |
|
175 |
5798
|
176 disp (["testing ", __f1, "\ninit: ", __init]); |
5589
|
177 |
|
178 ## make sure the functions are freshly loaded by evaluating them at |
5798
|
179 ## test_n(1); first have to initialize the args though. |
5589
|
180 n=1; k=0; |
|
181 eval ([__init, ";"]); |
|
182 if !isempty(__f2), eval ([__f2, ";"]); endif |
|
183 eval ([__f1, ";"]); |
|
184 |
|
185 ## run the tests |
|
186 for k=1:length(__test_n) |
5798
|
187 n=__test_n(k); |
|
188 eval ([__init, ";"]); |
5589
|
189 |
|
190 printf ("n%i=%i ",k, n) ; fflush(1); |
|
191 eval (["__t=time();", __f1, "; __v1=ans; __t = time()-__t;"]); |
|
192 if (__t < 0.25) |
|
193 eval (["__t2=time();", __f1, "; __t2 = time()-__t2;"]); |
|
194 eval (["__t3=time();", __f1, "; __t3 = time()-__t3;"]); |
|
195 __t = min([__t,__t2,__t3]); |
|
196 endif |
|
197 __tnew(k) = __t; |
|
198 |
|
199 if !isempty(__f2) |
|
200 eval (["__t=time();", __f2, "; __v2=ans; __t = time()-__t;"]); |
|
201 if (__t < 0.25) |
|
202 eval (["__t2=time();", __f2, "; __t2 = time()-__t2;"]); |
|
203 eval (["__t3=time();", __f2, "; __t3 = time()-__t3;"]); |
|
204 endif |
|
205 __torig(k) = __t; |
|
206 if !isinf(__tol) |
5798
|
207 assert(__v1,__v2,__tol); |
5589
|
208 endif |
|
209 endif |
|
210 |
5798
|
211 endfor |
5589
|
212 |
5798
|
213 ## Drop times of zero |
|
214 if !isempty(__f2) |
|
215 zidx = ( __tnew < 100*eps | __torig < 100*eps ) ; |
|
216 __test_n(zidx) = []; |
|
217 __tnew(zidx) = []; |
|
218 __torig(zidx) = []; |
5589
|
219 else |
5798
|
220 zidx = ( __tnew < 100*eps ) ; |
|
221 __test_n(zidx) = []; |
|
222 __tnew(zidx) = []; |
5589
|
223 endif |
5798
|
224 |
|
225 ## Approximate time complexity and return it if requested |
|
226 tailidx = [ceil(length(__test_n)/2):length(__test_n)]; |
|
227 p = polyfit(log(__test_n(tailidx)),log(__tnew(tailidx)), 1); |
|
228 if nargout > 0, |
|
229 __order.p = p(1); |
|
230 __order.a = exp(p(2)); |
|
231 endif |
|
232 |
5589
|
233 |
5798
|
234 ## Plot the data if no output is requested. |
|
235 doplot = (nargout == 0); |
|
236 |
|
237 if doplot && !isempty(__f2) |
|
238 |
5589
|
239 |
|
240 subplot(121); |
|
241 xlabel("test length"); |
|
242 title (__f1); |
|
243 ylabel("speedup ratio"); |
5798
|
244 semilogx ( __test_n, __torig./__tnew, |
5589
|
245 ["-*r;", strrep(__f1,";","."), "/", strrep(__f2,";","."), ";"], |
5798
|
246 __test_n, __tnew./__torig, |
5589
|
247 ["-*g;", strrep(__f2,";","."), "/", strrep(__f1,";","."), ";"]); |
|
248 subplot (122); |
|
249 |
|
250 ylabel ("best execution time (ms)"); |
|
251 title (["init: ", __init]); |
5798
|
252 loglog ( __test_n, __tnew*1000, ["*-g;", strrep(__f1,";","."), ";" ], |
|
253 __test_n, __torig*1000, ["*-r;", strrep(__f2,";","."), ";"]) |
|
254 |
|
255 ratio = mean (__torig ./ __tnew); |
|
256 printf ("\n\nMean runtime ratio = %.3g for '%s' vs '%s'\n", ... |
|
257 ratio, __f2, __f1); |
|
258 |
|
259 elseif doplot |
|
260 |
|
261 subplot(111); |
5589
|
262 xlabel("test length"); |
|
263 ylabel ("best execution time (ms)"); |
|
264 title ([__f1, " init: ", __init]); |
5798
|
265 loglog ( __test_n, __tnew*1000, "*-g;execution time;"); |
|
266 |
5589
|
267 endif |
5798
|
268 |
|
269 if doplot |
|
270 |
|
271 ## Plot time complexity approximation (using milliseconds). |
|
272 order = sprintf("O(n^%g)",round(10*p(1))/10); |
|
273 v = polyval(p,log(__test_n(tailidx))); |
|
274 hold on; |
|
275 loglog(__test_n(tailidx), exp(v)*1000, sprintf("b;%s;",order)); |
|
276 hold off; |
|
277 |
|
278 ## Get base time to 1 digit of accuracy |
|
279 dt = exp(p(2)); |
|
280 dt = floor(dt/10^floor(log10(dt)))*10^floor(log10(dt)); |
|
281 if log10(dt) >= -0.5, time = sprintf("%g s", dt); |
|
282 elseif log10(dt) >= -3.5, time = sprintf("%g ms", dt*1e3); |
|
283 elseif log10(dt) >= -6.5, time = sprintf("%g us", dt*1e6); |
|
284 else time = sprintf("%g ns", dt*1e9); |
|
285 endif |
|
286 |
|
287 ## Display nicely formatted complexity. |
|
288 printf ("\nFor %s:\n",__f1); |
|
289 printf (" asymptotic power: %s\n", order); |
|
290 printf (" approximate time per operation: %s\n", time); |
|
291 |
|
292 endif |
|
293 |
5589
|
294 endfunction |
|
295 |
|
296 %!demo if 1 |
|
297 %! function x = build_orig(n) |
|
298 %! ## extend the target vector on the fly |
|
299 %! for i=0:n-1, x([1:10]+i*10) = 1:10; endfor |
|
300 %! endfunction |
|
301 %! function x = build(n) |
|
302 %! ## preallocate the target vector |
|
303 %! x = zeros(1, n*10); |
|
304 %! try |
|
305 %! if (prefer_column_vectors), x = x.'; endif |
|
306 %! catch |
|
307 %! end |
|
308 %! for i=0:n-1, x([1:10]+i*10) = 1:10; endfor |
|
309 %! endfunction |
|
310 %! |
|
311 %! disp("-----------------------"); |
|
312 %! type build_orig; |
|
313 %! disp("-----------------------"); |
|
314 %! type build; |
|
315 %! disp("-----------------------"); |
|
316 %! |
|
317 %! disp("Preallocated vector test.\nThis takes a little while..."); |
|
318 %! speed('build', 'build_orig', 1000, 'v=n;'); |
|
319 %! clear build build_orig |
|
320 %! disp("Note how much faster it is to pre-allocate a vector."); |
|
321 %! disp("Notice the peak speedup ratio."); |
|
322 %! clear build build_orig |
|
323 %! endif |
|
324 |
|
325 %!demo if 1 |
|
326 %! function x = build_orig(n) |
|
327 %! for i=0:n-1, x([1:10]+i*10) = 1:10; endfor |
|
328 %! endfunction |
|
329 %! function x = build(n) |
|
330 %! idx = [1:10]'; |
|
331 %! x = idx(:,ones(1,n)); |
|
332 %! x = reshape(x, 1, n*10); |
|
333 %! try |
|
334 %! if (prefer_column_vectors), x = x.'; endif |
|
335 %! catch |
|
336 %! end |
|
337 %! endfunction |
|
338 %! |
|
339 %! disp("-----------------------"); |
|
340 %! type build_orig; |
|
341 %! disp("-----------------------"); |
|
342 %! type build; |
|
343 %! disp("-----------------------"); |
|
344 %! |
|
345 %! disp("Vectorized test. This takes a little while..."); |
|
346 %! speed('build', 'build_orig', 1000, 'v=n;'); |
|
347 %! clear build build_orig |
|
348 %! disp("-----------------------"); |
|
349 %! disp("This time, the for loop is done away with entirely."); |
|
350 %! disp("Notice how much bigger the speedup is then in example 1."); |
|
351 %! endif |