Waiting for the waitbar

I love matlab waitbar. I use it everywhere in my matlab code. I always have the feeling my code is running faster when a nice window show the progress of calculations being done. What a surprise I had  when I realized that Matlab waitbar function was significantly slowing down all my calculations.

h=waitbar(0,'Waiting...');
EndOfLoop=2000;
for i=1:EndOfLoop
waitbar(i/EndOfLoop,h);
end
delete(h);

If you run the following line while the Profiler is On, you will be very surprised. On my computer, a single update of the waitbar takes 30 ms. Now you will think that is not so much, but it is actually A LOT. As you can see just browsing through a for loop with 200 iterations takes 6 seconds ONLY because of the waitbar. This is rather slow.

A simple 100×100 matrix multiplications element wise (so about 10^4 multiplications at each iterations) take 100 times less time!

I did try to speed this up by looking at lower levels calls to the waitbar but Mathworks made it so nice and secure that you can’t access these.

So here is a work-around solutions (Until Mathworks actually fixes this issue). This is not of the best elegance but it works reliably : just limit your access to the function to just what is needed to inform you or your users of the current progress.

h=waitbar(0,'Waiting...');
EndOfLoop=200;

dividerWaitbar=10^(floor(log10(EndOfLoop))-1);

for i=1:EndOfLoop
if (round(i/dividerWaitbar)==i/dividerWaitbar)
waitbar(i/EndOfLoop,h);
end
end
delete(h);

This code just work out the biggest divider to limit waitbar access and keep  the number of calls to waitbar always in the tens whatever the number of iterations. The use of the logarithmic function is just to make sure it works as well for big or small numbers below 10.

NOTA : I submitted a bug report to Matlab about this issue as this is not a normal behavior. It was confirmed as an enhancement request. We will see if it is incorporated in Matlab 2013. In the meantime, I also recommend using multiWaitbar on the file exchange (from Mathworks actually) which is far more efficient, provides a better look and is more flexible. 

This entry was posted in Annoyances, Intermediate, Making interfaces, Optimizing your code. Bookmark the permalink.

Leave a Reply