Undocumented Matlab
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT

Pause for the better

August 29, 2012 17 Comments

A few days ago, blog reader Tomás Peyré commented on the fact that the pause function has a memory leak on R2011b and R2012a, and advised using the Java Thread.sleep() function instead. This got me started on a comparison between these seemingly-equivalent functions. It turns out that the Java variant not only does not leak memory like its Matlab counterpart pause – the Java function is also much more accurate in its pause duration.
Testing the pause accuracy is quite simple: Simply pause a pre-defined duration and measure the actual time span. I run this 100 times to get some meaningful statistics. Note that the only difference between the loops below is the pause function that is being used (see highlighted rows):

% Some initializations
timesToRun = 100;
duration = 0.25;  % [secs]
% Measure Matlab's pause() accuracy
tPause(timesToRun) = 0;  % pre-allocate
for idx = 1 : timesToRun
   tic
   pause(duration);                        % Note: pause() accepts [Secs] duration
   tPause(idx) = abs(toc-duration);end
% Measure Java's sleep() accuracy
tSleep(timesToRun) = 0;  % pre-allocate
for idx=1 : timesToRun
   tic
   java.lang.Thread.sleep(duration*1000);  % Note: sleep() accepts [mSecs] duration
   tSleep(idx) = abs(toc-duration);
end

% Some initializations timesToRun = 100; duration = 0.25; % [secs] % Measure Matlab's pause() accuracy tPause(timesToRun) = 0; % pre-allocate for idx = 1 : timesToRun tic pause(duration); % Note: pause() accepts [Secs] duration tPause(idx) = abs(toc-duration); end % Measure Java's sleep() accuracy tSleep(timesToRun) = 0; % pre-allocate for idx=1 : timesToRun tic java.lang.Thread.sleep(duration*1000); % Note: sleep() accepts [mSecs] duration tSleep(idx) = abs(toc-duration); end

The results are consistent and conclusive:

Function median inaccuracy mean inaccuracy max inaccuracy max inaccuracy as % of total (250 mSec)
Matlab’s pause() 2.0 mSec 3.6 mSec 12.8 mSec 5.1%
Java’s Thread.sleep() 0.01 mSec 0.02 mSec 0.53 mSec 0.2%


When the pause duration is reduced to 50 mSecs (0.05 secs), the results are even more striking:

Function median inaccuracy mean inaccuracy max inaccuracy max inaccuracy as % of total (50 mSec)
Matlab’s pause() 11.6 mSec 12.5 mSec 15.5 mSec 31%
Java’s Thread.sleep() 0.78 mSec 0.77 mSec 0.84 mSec 1.7%

When the pause duration is further reduced, Matlab’s inaccuracies increase (120% at 0.01, 370% at 0.005) to a point where we cannot in practice rely on them. Apparently, Matlab’s pause function has an inherent inaccuracy of several mSecs that increases as the pause duration decreases. The effect of increasing absolute inaccuracy with decreasing total pause duration is catastrophic. On the other hand, Java’s inaccuracy remains stable at <1 mSec, making its relative inaccuracy degradation much more gradual and acceptable (8% at 0.01, 20% at 0.005).
Matlab’s pause function has an important side-effect, that may partly explain the discrepancy: Whenever pause is called, the graphics event queue (EDT) is flushed, thereby updating all Matlab figure windows. In my tests above I did not have any open figures, otherwise I suspect the discrepancy would only have been larger. This side effect is actually quite important when integrating Java GUI components in Matlab figures.
Java’s Thread.sleep function, like Matlab’s pause(), is not guaranteed to pause for the exact duration specified. However, as the above results clearly show, in practice the Java variant is much more accurate than Matlab’s. So if you want accurate and leak-free pauses, and do not need the EDT side-effect, I really see no reason to use Matlab’s pause. Sleep() over it…

Related posts:

  1. Waiting for asynchronous events – The Matlab waitfor function can be used to wait for asynchronous Java/ActiveX events, as well as with timeouts. ...
  2. tic / toc – undocumented option – Matlab's built-in tic/toc functions have an undocumented option enabling multiple nested clockings...
  3. Improving save performance – There are many different ways of improving Matlab's standard save function performance. ...
  4. Function call timeline profiling – A new utility enables to interactively explore Matlab function call timeline profiling. ...
  5. File deletion memory leaks, performance – Matlab's delete function leaks memory and is also slower than the equivalent Java function. ...
  6. Matlab-Java memory leaks, performance – Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...
Java Performance
Print Print
« Previous
Next »
17 Responses
  1. the cyclist September 4, 2012 at 07:58 Reply

    A couple comments:

    First, the results may be platform-dependent. Running R2012a on a Mac (OS X 10.6.8), I get more comparable inaccuracies for MATLAB and Java. Mean inaccuracy for MATLAB is about 0.38 msec, and Java is about 0.26 msec. Also, unlike your results, those inaccuracies are roughly constant when I reduce the input duration.

    Second, I notice that one does not need to take the absolute value as you did. The error is systematically positive. This is presumably because both MATLAB and Java choose to pause for at least the prescribed duration.

    • Yair Altman September 4, 2012 at 08:04 Reply

      @Tim – Thanks for your comments. Unfortunately, at least on Windows the error is sometimes negative, hence my use of abs().

  2. Andrew September 6, 2012 at 07:56 Reply

    Hi Yair,
    I have noticed that there are issues with MATLAB hanging up when using inputdlg and other modal dialog boxes. These issues are solved by putting a pause after the dialog box is closed. I’m assuming this has to do with the queue being flushed, as you mentioned. Is there a different way to deal with these issues other than using pause?
    Thanks!
    ~Andrew

    • Andrew September 6, 2012 at 07:59 Reply

      It looks like using drawnow has the same effect.
      Thanks!
      ~Andrew

    • Yair Altman September 6, 2012 at 08:07 Reply

      @Andrew – thanks for mentioning this. This is indeed the case, and quite possibly deserves a dedicated article because it is such a frustrating and common issue, that exists in many Matlab releases, and because the solution (adding a pause or drawnow) is so frustratingly simple and yet undocumented. As noted here, drawnow is similar but not exactly the same as pause. I often use both of them, since I found out by trial-and-error that different situations respond better to either of them, and I never remember which one to use… So I often have lines such as the following scattered around my code (I know it’s ugly, but it works and that’s what matters in the end):

      drawnow; pause(0.05);  % or reverse this order

      drawnow; pause(0.05); % or reverse this order

      To your question, I do not know of any simpler or better way to solve these hangups.

  3. Ang October 17, 2012 at 01:23 Reply

    Hi,

    Nice article!

    It turns out that I could handle an event during pause, but not when I use Thread.sleep.

    For example, it’s possible for an event handler to do something to interrupt the while loop here:

    global KeepRunning
    KeepRunning = true;
    while (KeepRunning)
      pause(.001)
      % It's possible for the event handler to change KeepRunning to false when an event is fired.
    end

    global KeepRunning KeepRunning = true; while (KeepRunning) pause(.001) % It's possible for the event handler to change KeepRunning to false when an event is fired. end

    Yet, this is not possible when Thread.Sleep is used.

    global KeepRunning
    KeepRunning = true;
    while (KeepRunning)
      java.lang.Thread.sleep(1);
      % This loop will continue running, no chance is given to the event handler to do anything.
    end

    global KeepRunning KeepRunning = true; while (KeepRunning) java.lang.Thread.sleep(1); % This loop will continue running, no chance is given to the event handler to do anything. end

    Do you experience the same thing? I’m using Windows 32-bit MATLAB. In any case, I’d like to try and see where I can put Thread.sleep for my future MATLAB programs.

    Regards,
    YA

    • Yair Altman October 17, 2012 at 11:47 Reply

      @Ang – yes, I have also seen this. I am not exactly sure why this happens. It is probably EDT-related, but I am not sure exactly how or why.

    • kits November 2, 2012 at 11:55 Reply

      Try adding a “drawnow;” in that loop?

    • Doug January 30, 2013 at 13:18 Reply

      Thanks for the `drawnow;` recommendation! It made this all work perfectly for me.

  4. Marc February 5, 2013 at 03:48 Reply

    The following patch worked for me to correct this memory (and windows handle!) leak on 2012b:
    http://www.mathworks.com/support/bugreports/819115

    Since the problem seems to be inside drawnow, using sleep+drawnow probably doesn’t help.

    • Yair Altman February 5, 2013 at 04:09 Reply

      @Marc – thanks for sharing. According to the patch description, it is not directly related to pause, but perhaps the issues are somehow related.

    • Marc February 5, 2013 at 04:38 Reply

      As far as I can see, pause() calls (a part of) drawnow to flush the queue. Interesting: with Process Explorer I found that pause() leaks semaphore handles as well as memory, so the flush probably forgets to clean up a semaphore object…

  5. Solving a Matlab hang problem | Undocumented Matlab February 6, 2013 at 11:01 Reply

    […] a reader’s comment yesterday happened on the same page where I explained the problem and solution […]

  6. Take a break, have a pause() | matlabideas May 18, 2013 at 07:54 Reply

    […] time ago my colleague showed me an article from Undocumented MATLAB that argues in favour of the Java Thread.sleep() function instead of the MATLAB pause() […]

  7. Sometalk August 16, 2018 at 12:53 Reply

    Have you rerun this benchmark more recently? I wonder if there have been any improvements in this space.

    • Yair Altman August 16, 2018 at 14:35 Reply

      In recent Matlab releases, Matlab’s pause is no less (sometimes even more) accurate than Java’s Thread.sleep, with a consistent mean inaccuracy (overhead) of 0.1-0.2 ms and max inaccuracy of ~1ms, regardless of the pause duration. These values depend of course on the specific OS and CPU, so YMMV.

  8. Dima May 9, 2019 at 11:25 Reply

    Hey Yair,
    As you said, in the new MATLAB versions the pause performs the same or even better for some pause duration. The interesting thing is that for time duration in between >1ms and <10ms Java's sleep performs better (see a table below) but for duration less than equal to 1ms MATLAB the opposite is true.
    Do you have any idea why is this?
    Also does it make any sense at all to measure pausing time for duration less than 1ms? (Can tic/toc give reliable values for this small time period?)
    ============================================================
    Pausing Time = 10ms :
    pause() : Median = 5.6129 Mean = 5.3252 Max = 12.1966
    sleep() : Median = 5.6125 Mean = 5.4652 Max = 14.849
    ============================================================
    Pausing Time = 7ms :
    pause() : Median = 8.6154 Mean = 7.7185 Max = 14.0192
    sleep() : Median = 0.3767 Mean = 0.60192 Max = 1.3815
    ============================================================
    Pausing Time = 5ms :
    pause() : Median = 10.6026 Mean = 8.8543 Max = 15.4677
    sleep() : Median = 0.38281 Mean = 0.57611 Max = 1.4071
    ============================================================
    Pausing Time = 1ms :
    pause() : Median = 0.0076145 Mean = 0.015155 Max = 0.31958
    sleep() : Median = 0.34215 Mean = 0.53122 Max = 1.5084
    ============================================================

Leave a Reply
HTML tags such as <b> or <i> are accepted.
Wrap code fragments inside <pre lang="matlab"> tags, like this:
<pre lang="matlab">
a = magic(3);
disp(sum(a))
</pre>
I reserve the right to edit/delete comments (read the site policies).
Not all comments will be answered. You can always email me (altmany at gmail) for private consulting.

Click here to cancel reply.

Useful links
  •  Email Yair Altman
  •  Subscribe to new posts (feed)
  •  Subscribe to new posts (reader)
  •  Subscribe to comments (feed)
 
Accelerating MATLAB Performance book
Recent Posts

Speeding-up builtin Matlab functions – part 3

Improving graphics interactivity

Interesting Matlab puzzle – analysis

Interesting Matlab puzzle

Undocumented plot marker types

Matlab toolstrip – part 9 (popup figures)

Matlab toolstrip – part 8 (galleries)

Matlab toolstrip – part 7 (selection controls)

Matlab toolstrip – part 6 (complex controls)

Matlab toolstrip – part 5 (icons)

Matlab toolstrip – part 4 (control customization)

Reverting axes controls in figure toolbar

Matlab toolstrip – part 3 (basic customization)

Matlab toolstrip – part 2 (ToolGroup App)

Matlab toolstrip – part 1

Categories
  • Desktop (45)
  • Figure window (59)
  • Guest bloggers (65)
  • GUI (165)
  • Handle graphics (84)
  • Hidden property (42)
  • Icons (15)
  • Java (174)
  • Listeners (22)
  • Memory (16)
  • Mex (13)
  • Presumed future risk (394)
    • High risk of breaking in future versions (100)
    • Low risk of breaking in future versions (160)
    • Medium risk of breaking in future versions (136)
  • Public presentation (6)
  • Semi-documented feature (10)
  • Semi-documented function (35)
  • Stock Matlab function (140)
  • Toolbox (10)
  • UI controls (52)
  • Uncategorized (13)
  • Undocumented feature (217)
  • Undocumented function (37)
Tags
ActiveX (6) AppDesigner (9) Callbacks (31) Compiler (10) Desktop (38) Donn Shull (10) Editor (8) Figure (19) FindJObj (27) GUI (141) GUIDE (8) Handle graphics (78) HG2 (34) Hidden property (51) HTML (26) Icons (9) Internal component (39) Java (178) JavaFrame (20) JIDE (19) JMI (8) Listener (17) Malcolm Lidierth (8) MCOS (11) Memory (13) Menubar (9) Mex (14) Optical illusion (11) Performance (78) Profiler (9) Pure Matlab (187) schema (7) schema.class (8) schema.prop (18) Semi-documented feature (6) Semi-documented function (33) Toolbar (14) Toolstrip (13) uicontrol (37) uifigure (8) UIInspect (12) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
  • Nicholas (6 days 11 hours ago): Hi Yair, Thanks for the reply. I am on Windows 10. I also forgot to mention that this all works wonderfully out of the editor. It only fails once compiled. So, yes, I have tried a...
  • Nicholas (6 days 11 hours ago): Hi Yair, Thanks for the reply. I am on Windows 10. I also forgot to mention that this all works wonderfully out of the editor. It only fails once compiled. So, yes, I have tried a...
  • Yair Altman (6 days 18 hours ago): Nicholas – yes, I used it in a compiled Windows app using R2022b (no update). You didn’t specify the Matlab code location that threw the error so I can’t help...
  • Nicholas (7 days 15 hours ago): Hi Yair, Have you attempted your displayWebPage utility (or the LightweightHelpPanel in general) within a compiled application? It appears to fail in apps derived from both R2022b...
  • João Neves (10 days 19 hours ago): I am on matlab 2021a, this still works: url = struct(struct(struct(struct(hF ig).Controller).PlatformHost). CEF).URL; but the html document is empty. Is there still a way to do...
  • Yair Altman (13 days 18 hours ago): Perhaps the class() function could assist you. Or maybe just wrap different access methods in a try-catch so that if one method fails you could access the data using another...
  • Jeroen Boschma (13 days 21 hours ago): Never mind, the new UI components have an HTML panel available. Works for me…
  • Alexandre (13 days 22 hours ago): Hi, Is there a way to test if data dictionnatry entry are signal, simulink parameters, variables … I need to access their value, but the access method depends on the data...
  • Nicholas (14 days 12 hours ago): In case anyone is looking for more info on the toolbar: I ran into some problems creating a toolbar with the lightweight panel. Previously, the Browser Panel had an addToolbar...
  • Jeroen Boschma (17 days 19 hours ago): I do not seem to get the scrollbars (horizontal…) working in Matlab 2020b. Snippets of init-code (all based on Yair’s snippets on this site) handles.text_explorer...
  • Yair Altman (45 days 21 hours ago): m_map is a mapping tool, not even created by MathWorks and not part of the basic Matlab system. I have no idea why you think that the customizations to the builtin bar function...
  • chengji chen (46 days 3 hours ago): Hi, I have tried the method, but it didn’t work. I plot figure by m_map toolbox, the xticklabel will add to the yticklabel at the left-down corner, so I want to move down...
  • Yair Altman (53 days 20 hours ago): @Alexander – this is correct. Matlab stopped including sqlite4java in R2021b (it was still included in 21a). You can download the open-source sqlite4java project from...
  • Alexander Eder (59 days 16 hours ago): Unfortunately Matlab stopped shipping sqlite4java starting with R2021(b?)
  • K (66 days 3 hours ago): Is there a way to programmatically manage which figure gets placed where? Let’s say I have 5 figures docked, and I split it into 2 x 1, I want to place 3 specific figures on the...
Contact us
Captcha image for Custom Contact Forms plugin. You must type the numbers shown in the image
Undocumented Matlab © 2009 - Yair Altman
This website and Octahedron Ltd. are not affiliated with The MathWorks Inc.; MATLAB® is a registered trademark of The MathWorks Inc.
Scroll to top