<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Profiler &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/profiler/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 18 May 2016 18:00:37 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>
	<item>
		<title>Viewing saved profiling results</title>
		<link>https://undocumentedmatlab.com/articles/viewing-saved-profiling-results?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=viewing-saved-profiling-results</link>
					<comments>https://undocumentedmatlab.com/articles/viewing-saved-profiling-results#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 18 May 2016 18:00:37 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Profiler]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6421</guid>

					<description><![CDATA[<p>We can easily use saved profiling results to analyze, view and compare profiling results of multiple runs. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/viewing-saved-profiling-results">Viewing saved profiling results</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/function-call-timeline-profiling" rel="bookmark" title="Function call timeline profiling">Function call timeline profiling </a> <small>A new utility enables to interactively explore Matlab function call timeline profiling. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/profiling-matlab-memory-usage" rel="bookmark" title="Profiling Matlab memory usage">Profiling Matlab memory usage </a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4" rel="bookmark" title="Undocumented Profiler options part 4">Undocumented Profiler options part 4 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 4 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-3" rel="bookmark" title="Undocumented Profiler options part 3">Undocumented Profiler options part 3 </a> <small>An undocumented feature of the Matlab Profiler can report call history timeline - part 3 of series. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Many Matlab users know and utilize <a href="http://www.mathworks.com/help/matlab/matlab_prog/profiling-for-improving-performance.html" rel="nofollow" target="_blank">Matlab&#8217;s built-in Profiler tool</a> to identify performance bottlenecks and code-coverage issues. Unfortunately, not many are aware of the Profiler&#8217;s programmatic interface. In past articles as well as my performance book I <a href="/articles/undocumented-profiler-options-part-3" target="_blank">explained</a> how we can use this programmatic interface to save profiling results and analyze it offline. In fact, I took this idea further and even created a utility (<a href="/articles/function-call-timeline-profiling" target="_blank"><i><b>profile_history</b></i></a>) that displays the function call timeline in a standalone Matlab GUI, something that is a sorely missed feature in the built-in profiler:<br />
<center><a target="_blank" href="/images/profile_history.png"><img decoding="async" alt="Function call timeline profiling (click for full-size image)" src="https://undocumentedmatlab.com/images/profile_history.png" title="Function call timeline profiling (click for full-size image)" width="100%" style="max-width: 658px;" /></a><br />
Function call timeline profiling (click for full-size image)</center><br />
Today I will discuss a related undocumented feature of the Profiler: loading and viewing pre-saved profiling results.<br />
<span id="more-6421"></span></p>
<h3 id="output">Programmatic access to profiling results</h3>
<p>Matlab&#8217;s syntax for returning the detailed profiling results in a data struct is clearly documented in the <a href="http://www.mathworks.com/help/matlab/ref/profile.html#bux4pud-1" rel="nofollow" target="_blank"><i><b>profile</b></i> function&#8217;s doc page</a>. Although the documentation does not explain the resulting struct and sub-struct fields, they have meaningful names and we can relatively easily infer what each of them means (I added a few annotation comments for clarity):</p>
<pre lang="matlab">
>> profile('on','-history')
>> surf(peaks); drawnow
>> profile('off')
>> profData = profile('info')
profData =
      FunctionTable: [26x1 struct]
    FunctionHistory: [2x56 double]
     ClockPrecision: 4.10517962829241e-07
         ClockSpeed: 2501000000
               Name: 'MATLAB'
           Overhead: 0
>> profData.FunctionTable(1)
ans =
          CompleteName: 'C:\Program Files\Matlab\R2016a\toolbox\matlab\specgraph\peaks.m>peaks'
          FunctionName: 'peaks'
              FileName: 'C:\Program Files\Matlab\R2016a\toolbox\matlab\specgraph\peaks.m'
                  Type: 'M-function'
              Children: [1x1 struct]
               Parents: [0x1 struct]
         ExecutedLines: [9x3 double]
           IsRecursive: 0
    TotalRecursiveTime: 0
           PartialData: 0
              NumCalls: 1
             TotalTime: 0.0191679078068094
>> profData.FunctionTable(1).Children
ans =
        Index: 2   % index in profData.FunctionTable array
     NumCalls: 1
    TotalTime: 0.00136415141013509
>> profData.FunctionTable(1).ExecutedLines   % line number, number of calls, duration in secs
ans =
         43      1      0.000160102031282782
         44      1      2.29890096200918e-05
         45      1      0.00647592190637408
         56      1      0.0017093970724654
         57      1      0.00145036019621044
         58      1      0.000304193859437286
         60      1      4.39254290955326e-05
         62      1      3.44835144301377e-05
         63      1      0.000138755093778411
>> profData.FunctionHistory(:,1:5)
ans =
     0     0     1     1     0   % 0=enter, 1=exit
     1     2     2     1     6   % index in profData.FunctionHistory array
</pre>
<p>As we can see, this is pretty intuitive so far.</p>
<h3 id="viewing">Loading and viewing saved profiling results</h3>
<p>If we wish to save these results results in a file and later load and display them in the Profiler&#8217;s visualization browser, then we need to venture deeper into undocumented territory. It seems that while retrieving the profiling results (via <i><b>profile</b>(&#8216;info&#8217;)</i>) is fully documented, doing the natural complementary action (namely, loading this data into the viewer) is not. For the life of me I cannot understand the logic behind this decision, but that&#8217;s the way it is.<br />
Luckily, the <a href="/articles/legend-semi-documented-feature#Semi-documented" target="_blank">semi-documented built-in function</a> <i><b>profview</b></i> does exactly what we need: <i><b>profview</b></i> accepts 2 input args (function name and the <code>profData</code> struct) and displays the resulting profiling info. The first input arg (function name) accepts either a string (e.g., <code>'peaks'</code> or <code>'view>isAxesHandle'</code>), or the numeric value 0 which signifies the home (top-level) page:</p>
<pre lang="matlab">
profView(0, profData);  % display profiling home (top-level) page
profview('peaks', profData);  % display a specific profiling page
</pre>
<p>I use the 0 input value much more frequently than the string inputs, because I often don&#8217;t know which functions exactly were profiled, and starting at the home page enables me to easily drill-down the profiling results interactively.</p>
<h3 id="viewing">Loading saved profiling results from a different computer</h3>
<p>Things get slightly complicated if we try to load saved profiling results from a different computer. If the other computer has exactly the same folder structure as our computer, and all our Matlab functions reside in exactly the same disk folders/path, then everything will work out of the box. The problem is that in general the other computer will have the functions in different folders. When we then try to load the <code>profData</code> on our computer, it will not find the associated Matlab functinos in order to display the line-by-line profiling results. We will only see the profiling data at the function level, not line level. This significantly reduces the usefulness of the profiling data. The Profiler page will display the following error message:<br />
<center><span style="background: #FFC0C0;"><code>This file was modified during or after profiling. Function listing disabled.</code></span></center><br />
We can solve this problem in either of two ways:</p>
<ol>
<li>Modify our <code>profData</code> to use the correct folder path on the local computer, rather than the other computer&#8217;s path (which is invalid on the local computer). For example:
<pre lang="matlab">
% Save the profData on computer #1:
profData = profile('info');
save('profData.mat', 'profData');
% Load the profData on computer #2:
fileData = load('profData.mat');
profData = fileData.profData;
path1 = 'N:\Users\Juan\programs\myProgram';
path2 = 'C:\Yair\consulting\clients\Intel\code';
for idx = 1 : numel(profData.FunctionTable)
   funcData = profData.FunctionTable(idx);
   funcData.FileName     = strrep(funcData.FileName,     path1, path2);
   funcData.CompleteName = strrep(funcData.CompleteName, path1, path2);
   profData.FunctionTable(idx) = funcData;
end
% note: this loop can be vectorized if you wish
</pre>
</li>
<li>As an alternative, we can modify Matlab&#8217;s <i>profview.m</i> function (<i>%matlabroot%/toolbox/matlab/codetools/profview.m</i>) to search for the function&#8217;s source code in the current Matlab path, if the specified direct path is not found (note that changing <i>profview.m</i> may require administrator priviledges). For example, the following is the code from R2016a&#8217;s <i>profview.m</i> file, line #506:
<pre lang="matlab" highlight="3-5,7-9">
    % g894021 - Make sure the MATLAB code file still exists
    if ~exist(fullName, 'file')
        [~,fname,fext] = fileparts(fullName);  % Yair
        fname = which([fname fext]);           % Yair
        if isempty(fname)                      % Yair
            mFileFlag = 0;
        else                                   % Yair
            fullName = fname;                  % Yair
        end                                    % Yair
    end
</pre>
</li>
</ol>
<p>These two workarounds complement each other: the first workaround does not require changing any installed Matlab code, and so is platform- and release-independent, but would require rerunning the code snippet for each and every profiling data file that we receive from external computers. On the other hand, the second workaround is a one-time operation that should work for multiple saved profiling results, although we would need to redo it whenever we install Matlab.</p>
<h3 id="customizations">Additional <i><b>profview</b></i> customizations</h3>
<p>Modifying the <i>profview.m</i> function can be used for different improvements as well.<br />
For example, several years ago <a href="/articles/undocumented-profiler-options-part-2" target="_blank">I explained</a> how this function can be modified to display 1 ms timing resolutions, rather than the default 10 mS.<br />
Another customization that I often do after I install Matlab is to change the default setting of truncating function lines longer than 40 characters &#8211; I typically modify this to 60 or 80 (depending on the computer monitor&#8217;s size&#8230;). All we need to do is to update the <code>truncateDisplayName</code> sub-function within <i>profview.m</i> as follows (taken from R2016a again, line #1762):</p>
<pre lang="matlab" highlight="3">
function shortFileName = truncateDisplayName(longFileName,maxNameLen)
%TRUNCATEDISPLAYNAME  Truncate the name if it gets too long
maxNameLen = max(60,maxNameLen);  % Yair
shortFileName = escapeHtml(longFileName);
if length(longFileName) > maxNameLen,
    shortFileName = char(com.mathworks.util.FileUtils.truncatePathname( ...
        shortFileName, maxNameLen));
end
</pre>
<p>You can see additional undocumented profiling features in the &#8220;Related posts&#8221; section below, as well as in Chapter 2 of my book &#8220;<a href="/books/matlab-performance" target="_blank"><i>Accelerating MATLAB Performance</i></a>&#8220;.<br />
Do you have any other customization to the profiling results? If so, please share it in a comment.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/viewing-saved-profiling-results">Viewing saved profiling results</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/function-call-timeline-profiling" rel="bookmark" title="Function call timeline profiling">Function call timeline profiling </a> <small>A new utility enables to interactively explore Matlab function call timeline profiling. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/profiling-matlab-memory-usage" rel="bookmark" title="Profiling Matlab memory usage">Profiling Matlab memory usage </a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4" rel="bookmark" title="Undocumented Profiler options part 4">Undocumented Profiler options part 4 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 4 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-3" rel="bookmark" title="Undocumented Profiler options part 3">Undocumented Profiler options part 3 </a> <small>An undocumented feature of the Matlab Profiler can report call history timeline - part 3 of series. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/viewing-saved-profiling-results/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Buggy Profiler option</title>
		<link>https://undocumentedmatlab.com/articles/buggy-profiler-option?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=buggy-profiler-option</link>
					<comments>https://undocumentedmatlab.com/articles/buggy-profiler-option#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 31 Oct 2012 18:00:38 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Profiler]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3288</guid>

					<description><![CDATA[<p>a bug exists in the profiler that prevents usage of its documented CPU timing functionality. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/buggy-profiler-option">Buggy Profiler option</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/tic-toc-undocumented-option" rel="bookmark" title="tic / toc &#8211; undocumented option">tic / toc &#8211; undocumented option </a> <small>Matlab's built-in tic/toc functions have an undocumented option enabling multiple nested clockings...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options" rel="bookmark" title="Undocumented profiler options">Undocumented profiler options </a> <small>The Matlab profiler has some undocumented options that facilitate debugging memory bottlenecks and JIT (Just-In-Time Java compilation) problems....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4" rel="bookmark" title="Undocumented Profiler options part 4">Undocumented Profiler options part 4 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 4 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-2" rel="bookmark" title="Undocumented Profiler options part 2">Undocumented Profiler options part 2 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 2 of series. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>During my work on the recent series of articles on <a target="_blank" href="/articles/tag/profiler/">undocumented Profiler options</a>, I came across a very odd bug. Apparently, a major documented Profiler functionality has been dysfunctional since at least R2008a (and probably earlier), and AFAIK was not reported until now.<br />
The functionality in question is the Profiler&#8217;s documented ability to display results in either wall-clock (<i><b>profile</b> -timer real</i>) or CPU-time (<i><b>profile</b> -timer cpu</i>) modes. In fact, at least since R2008a and possibly sooner (I&#8217;m unsure about earlier releases), at least on Windows (I&#8217;m unsure about other platforms), both of these Profiler options provide wall-clock measurements &#8211; CPU-time measurements is not available. The irony is that CPU mode is stated in the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/profile.html#f8-629126">documentation</a> to be the Profiler&#8217;s default mode, and has been this way ever since this option was introduced about a decade ago.<br />
I used a very simple test harness &#8211; prepare the following function in <i>test.m</i>:</p>
<pre lang='matlab'>
function test
    pause(2)
end
</pre>
<p>And now run it in the Profiler:</p>
<pre lang='matlab'>
>> profile on -timer cpu
>> test
>> profile off; profile report
</pre>
<p>If everything had worked as documented, the Profiler report would show the <i>test</i> function as taking no time at all, or maybe only a few millisecs of overhead. In fact, this is exactly what we see in Matlab release R14 SP3 (7.1, dated 2005):<br />
<center><figure style="width: 318px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" alt="Correct CPU-time profiling report (R14 SP3)" src="https://undocumentedmatlab.com/images/profile_cpu-time_R14SP3.png" title="Correct CPU-time profiling report (R14 SP3)" width="318" height="205" /><figcaption class="wp-caption-text">Correct CPU-time profiling report (R14 SP3)</figcaption></figure></center><br />
Unfortunately, on R2008a and later (and possibly also some earlier releases), the same profiling run reports the timing as taking 2 full seconds (=wall-clock time):<br />
<center><figure style="width: 368px" class="wp-caption aligncenter"><img decoding="async" alt="Bug: wall-clock timing instead of CPU-time (R2008a+)" src="https://undocumentedmatlab.com/images/profile_cpu-time_R2008a.png" title="Bug: wall-clock timing instead of CPU-time (R2008a+)" width="368" height="213" /><figcaption class="wp-caption-text">Bug: wall-clock timing instead of CPU-time (R2008a+)</figcaption></figure></center><br />
<span id="more-3288"></span><br />
You might assume that the built-in <i><b>pause</b></i> function has a bug that causes it to churn the CPU, and in that case the Profiler&#8217;s report would be correct. However, a quick check in the Task Manager (I actually use <a target="_blank" rel="nofollow" href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx">Process Explorer</a> that I find much better) proves that this is not the case &#8211; no discernible CPU-time is used by the Matlab process during the <i><b>pause</b></i>.<br />
Somewhere between R2006a and R2008a a bug was introduced that caused the Profiler to only use wall-clock mode.<br />
Note that even in R14 SP3 the situation is not perfect: I have found that the default mode (i.e., when not specifying the <i>-timer</i> mode explicitly) is sometimes wall-clock and sometimes CPU, with no apparent consistency. However, if we explicitly use the <i>-timer</i> option, it works ok.<br />
It is strange that such a feature has escaped everyone&#8217;s attention (the community&#8217;s no less than MathWorks&#8217;) for so many years. It is true that this is not an often-used functionality, and it is also true that the <i><b>profile</b></i> function itself it way under-utilized by the general public. Still, anyone who needs to do serious performance tuning must have used this feature at some point in time. When performance-tuning code, it is very important to be aware of both the wall-clock and the CPU-time of the profiled program. Different tuning strategies apply to these two modes. Relying only on wall-clock timing can lead to incorrect conclusions about the application&#8217;s hotspots, and therefore to sub-optimal tuning. So I am very surprised that this bug was not reported until now. I&#8217;ve reported it (1-K1I06V) lately, and I really hope that it will be fixed in R2013a.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/buggy-profiler-option">Buggy Profiler option</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/tic-toc-undocumented-option" rel="bookmark" title="tic / toc &#8211; undocumented option">tic / toc &#8211; undocumented option </a> <small>Matlab's built-in tic/toc functions have an undocumented option enabling multiple nested clockings...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options" rel="bookmark" title="Undocumented profiler options">Undocumented profiler options </a> <small>The Matlab profiler has some undocumented options that facilitate debugging memory bottlenecks and JIT (Just-In-Time Java compilation) problems....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4" rel="bookmark" title="Undocumented Profiler options part 4">Undocumented Profiler options part 4 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 4 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-2" rel="bookmark" title="Undocumented Profiler options part 2">Undocumented Profiler options part 2 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 2 of series. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/buggy-profiler-option/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Undocumented Profiler options part 4</title>
		<link>https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=undocumented-profiler-options-part-4</link>
					<comments>https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 03 Oct 2012 18:00:54 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[callstats]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Profiler]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3206</guid>

					<description><![CDATA[<p>Several undocumented features of the Matlab Profiler can make it much more useful - part 4 of series. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4">Undocumented Profiler options part 4</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-3" rel="bookmark" title="Undocumented Profiler options part 3">Undocumented Profiler options part 3 </a> <small>An undocumented feature of the Matlab Profiler can report call history timeline - part 3 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options" rel="bookmark" title="Undocumented profiler options">Undocumented profiler options </a> <small>The Matlab profiler has some undocumented options that facilitate debugging memory bottlenecks and JIT (Just-In-Time Java compilation) problems....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-2" rel="bookmark" title="Undocumented Profiler options part 2">Undocumented Profiler options part 2 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 2 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/buggy-profiler-option" rel="bookmark" title="Buggy Profiler option">Buggy Profiler option </a> <small>a bug exists in the profiler that prevents usage of its documented CPU timing functionality. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Today&#8217;s article concludes my series on undocumented features of the Matlab Profiler. Past articles explained how to <a target="_blank" href="/articles/undocumented-profiler-options/">profile memory</a>, <a target="_blank" href="/articles/undocumented-profiler-options-part-2/">improve timing resolution and fix a font issue</a>, and <a target="_blank" href="/articles/undocumented-profiler-options-part-3">display the call history</a>. Today&#8217;s article will explain undocumented switches of the <i><b>profile</b></i> function that can be used to profile built-in functions, to report and remove the profiling overhead, plus a couple of as-yet-unsolved mysteries.</p>
<h3 id="builtins">Profiling built-in functions</h3>
<p>Built-in functions (e.g., <i><b>isempty, length, find</b></i>) are not monitored or displayed in the profiling summary by default. They are also not linkable to a detailed profiling report in the detailed report of any user function. So, if we have a code line such as the following, we cannot know how much time is spent in <i><b>length, find</b></i> as opposed to being spent in <i>userFunction</i>:</p>
<pre lang='matlab'>numResults = length(find(userFunction()));</pre>
<p>However, we can tell the profile to monitor and display built-in functions using the undocumented optional <code>-detail builtin</code> switch of the <i><b>profile</b></i> function:</p>
<pre lang='matlab'>
profile on –detail builtin
profile('on','-detail','builtin')   % an equivalent alternative
</pre>
<p>Alternately, we can use the undocumented built-in function <i><b>callstats</b></i> directly (as I already explained, the <i><b>profile</b></i> function is simply a convenient wrapper function to <i><b>callstats</b></i>):</p>
<pre lang='matlab'>callstats('level', 2);  % 1=mmex, 2=builtin</pre>
<p>The built-in functions will now be reported in the profiling summary and detailed reports, and will be linkable within the code lines of the detailed report.<br />
Note: old MATLAB releases also supported the &#8216;operator&#8217; detail level, which provided profiling information about built-in operators such as +. However, this level of detail is no longer supported in the latest MATLAB releases.<br />
The <i>-detail</i> switch can also be used with other <i><b>profile</b></i> switches. For example:</p>
<pre lang='matlab'>>> profile('on','-detail','builtin','-timestamp'); surf(peaks); profile('off')</pre>
<p>To return to the standard profiling level (&#8216;mmex&#8217;), run one of the following:</p>
<pre lang='matlab'>
profile on –detail mmex
profile('on','-detail','mmex')   % an equivalent alternative
callstats('level', 1);           % an equivalent alternative
</pre>
<h3 id="overhead">Profiling overhead removal</h3>
<p>The <code>-remove_overhead</code> switch checks the profiler&#8217;s own overhead and knows to remove this overhead from all relevant timing values. This is normally off by default, and returns <code>profData.overhead=0</code>. When turned on, it stores the computed profiling overhead in <code>profData.overhead</code>:<br />
<span id="more-3206"></span></p>
<pre lang='matlab'>
profile -remove_overhead on
profile('-remove_overhead','on')        % equivalent alternative
callstats('remove_sample_overhead',1);  % equivalent alternative
</pre>
<p>We need to make a small fix to the <i><b>profview</b></i> function (<i>%matlabroot%/toolbox/matlab/codetools/profview.m</i>), otherwise the profiling report will croak on an error. The fix is simple: replace the following code segment (lines #351-355 in the <i>profview.m</i> file of R2012a)</p>
<pre lang='matlab' escaped="true">
if profileInfo.Overhead==0
    s{end+1} = sprintf(['&lt;p&gt;<a name="selftimedef"></a>', getString(message('MATLAB:profiler:SelfTime1st')) ' ']);
else
    s{end+1} = sprintf(['&lt;p&gt;<a name="selftimedef"></a>', getString(message('MATLAB:profiler:SelfTime2nd', profileInfo.Overhead))]);
end
</pre>
<p>with this (changed line highlighted &#8211; note the extra <i><b>num2str</b></i>):</p>
<pre lang='matlab' escaped="true" highlight="4">
if profileInfo.Overhead==0
    s{end+1} = sprintf(['&lt;p&gt;<a name="selftimedef"></a>', getString(message('MATLAB:profiler:SelfTime1st')) ' ']);
else
    s{end+1} = sprintf(['&lt;p&gt;<a name="selftimedef"></a>', getString(message('MATLAB:profiler:SelfTime2nd', num2str(profileInfo.Overhead)))]);
end
</pre>
<p>Turning the overhead switch on causes the message at the bottom of the profiling summary report to change, from something that says:</p>
<blockquote><p>Self time is the time spent in a function excluding the time spent in its child functions. Self time also includes overhead resulting from the process of profiling. </p></blockquote>
<p>To this (the numeric value is the computed overhead, also reported in <code>profData.overhead</code>):</p>
<blockquote><p>Self time is the time spent in a function excluding both the time spent in its child functions and most of the overhead resulting from the process of profiling. <br />In the present run, self time excludes 0.80601 seconds of profiling overhead. The amount of remaining overhead reflected in self time cannot be determined.</p></blockquote>
<p>A similar customization needs to be done to fix an error arising from the use of the undocumented <i><b>profile -timer none</b></i> option. I don&#8217;t really see great value in running a Profiler without timing information, so I&#8217;ll skip this part here. If anyone has an idea what this could be used for, I&#8217;d be happy to hear.</p>
<h3 id="mysteries">[As-yet] unsolved mysteries</h3>
<p>To conclude my series on undocumented profiling options, a couple of unsolved mysteries:</p>
<h4 id="HW">hardware profiling</h4>
<p>The <i><b>profview.m</b></i> function has several references to hardware performance counter data, which, if available as fields in <code>profData.FunctionTable</code>, are displayed as separate columns to the left of the time column field in the code section, and also enabled for the sorting and highlighting drop-downs in the detailed profiling report. Separate monitored hardware events are stored in separate fields named <code>profData.FunctionTable.HW<i>event</i></code> (see the <i>getHwFields()</i> sub-function on lines 1557-1564). The mystery: how can we tell the Profiler to start hardware monitoring in a way that would add these HW fields to the collected <code>profData.FunctionTable</code>? Lines 1652-1653 give a hint:</p>
<pre lang='matlab'>
hw_events = callstats('hw_events');
match = strcmpi(['hw_' str],hw_events);
</pre>
<p>Unfortunately, at least on my system, <code>callstats('hw_events')</code> returns an empty cell array:</p>
<pre lang='matlab'>
>> hw_events = callstats('hw_events')
hw_events =
   Empty cell array: 1-by-0
</pre>
<p>So if anyone has an idea how to use these HW events, I&#8217;d be happy to hear &#8211; please leave a <a href="/articles/undocumented-profiler-options-part-4#respond">comment</a> below.</p>
<h4 id="parallel">parallel profiling</h4>
<p>Another mystery relates to the question of how to profile parallel Matlab code. The underlying Java object of the Profiler tool (<code>com.mathworks.mde.profiler.Profiler.getInstance</code>) contains the following tell-tale methods:<br />
<i></p>
<ul>
<li>getHtmlTextParallel(), setHtmlTextParallel()</li>
<li>getInstanceWithParallelOpts()</li>
<li>getSelectedLabsFromHtml()</li>
<li>setNumLabs()</li>
<li>setNumLabsParallel()</li>
<li>setSelectedLab()</li>
</ul>
<p></i><br />
I would have expected the parallel-enabled Profiler to be started using <code>com.mathworks.mde.profiler.Profiler.getInstanceWithParallelOpts.invoke()</code>. This does indeed start the Profiler, but I can&#8217;t see any difference between its output and that of the normal Profiler, even when I run parallel (<i><b>parfor</b></i>) code. It  definitely does not look like output from the Parallel Computing Toolbox (PCT)&#8217;s <i><b>mpiprofile</b></i> function.<br />
Perhaps these methods are used by <i><b>mpiprofile</b></i> internally? It could make sense for both <i><b>profile</b></i> and <i><b>mpiprofile</b></i> to share the same underlying profiler tool. On the other hand, if this were indeed the case then why would there be a reason for a separate <i><b>mpiprofile</b></i> function? Wouldn&#8217;t the standard <i><b>profile</b></i> function be sufficient?<br />
Anyway, if anyone has an idea how to use these methods in the standard profiler, perhaps to profile parallel applications without the need for <i><b>pmode</b></i>, I&#8217;d be happy to hear &#8211; please leave a <a href="/articles/undocumented-profiler-options-part-4#respond">comment</a> below.</p>
<h3 id="conclusion">Conclusion</h3>
<p>The Matlab Profiler has quite a few important features, which for some unknown reason have not been made public. Matlab&#8217;s Profiler has remained stagnant since Matlab 7 was released last decade. In fact, some functionality, like the <a target="_blank" href="/articles/undocumented-profiler-options/">JIT information feature</a>, was actually removed. Hopefully, future Matlab releases will improve the Profiler, by making these undocumented features officially supported, as well as by adding other important functionality.<br />
This concludes my series on undocumented profiling features in Matlab. If anyone knows any other Profiler tricks, please share them in a <a href="/articles/undocumented-profiler-options-part-4#respond">comment</a> below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4">Undocumented Profiler options part 4</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-3" rel="bookmark" title="Undocumented Profiler options part 3">Undocumented Profiler options part 3 </a> <small>An undocumented feature of the Matlab Profiler can report call history timeline - part 3 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options" rel="bookmark" title="Undocumented profiler options">Undocumented profiler options </a> <small>The Matlab profiler has some undocumented options that facilitate debugging memory bottlenecks and JIT (Just-In-Time Java compilation) problems....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-2" rel="bookmark" title="Undocumented Profiler options part 2">Undocumented Profiler options part 2 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 2 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/buggy-profiler-option" rel="bookmark" title="Buggy Profiler option">Buggy Profiler option </a> <small>a bug exists in the profiler that prevents usage of its documented CPU timing functionality. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Undocumented Profiler options part 3</title>
		<link>https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-3?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=undocumented-profiler-options-part-3</link>
					<comments>https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-3#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 26 Sep 2012 18:00:02 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[callstats]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Profiler]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3158</guid>

					<description><![CDATA[<p>An undocumented feature of the Matlab Profiler can report call history timeline - part 3 of series. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-3">Undocumented Profiler options part 3</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4" rel="bookmark" title="Undocumented Profiler options part 4">Undocumented Profiler options part 4 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 4 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options" rel="bookmark" title="Undocumented profiler options">Undocumented profiler options </a> <small>The Matlab profiler has some undocumented options that facilitate debugging memory bottlenecks and JIT (Just-In-Time Java compilation) problems....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-2" rel="bookmark" title="Undocumented Profiler options part 2">Undocumented Profiler options part 2 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 2 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/buggy-profiler-option" rel="bookmark" title="Buggy Profiler option">Buggy Profiler option </a> <small>a bug exists in the profiler that prevents usage of its documented CPU timing functionality. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Today&#8217;s article continues my series on undocumented features of the Matlab Profiler. Past articles explained how to <a target="_blank" href="/articles/undocumented-profiler-options/">profile memory</a>, <a target="_blank" href="/articles/undocumented-profiler-options-part-2/">improve timing resolution and fix a font issue</a>. Today&#8217;s article will explain undocumented switches of the <i><b>profile</b></i> function that can be used to provide detailed history timeline of the function calls. Next week&#8217;s article will conclude the series by explaining undocumented switches of the profile function that can be used to profile built-in functions, to report and remove the profiling overhead, plus a couple of as-yet-unsolved mysteries.</p>
<h3 id="history">Simple call history</h3>
<p>One of the features that the programmatic profiling interface provides, and which is not represented in the Profiler GUI, is a report of the exact order in which different functions were called during the profiling session. This profiling history can be turned on using the <code>–history</code> switch. There is also an optional switch of <code>–historysize</code>, which enables us to modify the history size from a default maximum of 1 million function entry and exit items. Here is a sample usage of this history feature:</p>
<pre lang='matlab'>
>> profile('on','-history'); surf(peaks); profile('off')
>> profData = profile('info');
>> history = profData.FunctionHistory
history =
  Columns 1 through 11
     0     0     0     1     0     1     0     1     1     1     0
    19     1    17    17    17    17    18    18     1    19     5
  ...
</pre>
<p>The history data is actually a numeric matrix, where the first row contains the values 0 (=function entry) or 1 (=function exit), and the second row is the corresponding index into <code>profData.FunctionTable</code>, indicating the called function. We can easily convert this matrix into human-readable form using the following code snippet:</p>
<pre lang='matlab'>
offset = cumsum(1-2*history(1,:)) - 1;  % calling depth
entryIdx = history(1,:)==1;     % history items of function entries
funcIdx = history(2,entryIdx);  % indexes of relevant functions
funcNames = {profData.FunctionTable(funcIdx).FunctionName};
for idx = 1: length(funcNames);
   disp([repmat(' ',1,offset(idx)) funcNames{idx}]);
end
</pre>
<p>which generates the following calling list in the MATLAB Command Window:</p>
<pre lang='matlab'>
isempty
 isempty
  transpose
 meshgrid
  peaks
 nargchk
  error
 ishg2parent
...
</pre>
<p>Unfortunately, the history information does not by default contain specific timing of each function entry/exit, but we can still make good use of it by looking at the sequence in which the functions were called from each other.</p>
<h3 id="detailed">Detailed call history, with timing information</h3>
<p>In order to retrieve actual history timing information, we can run profile with the undocumented/unsupported <code>–timestamp</code> switch, which stores the CPU clock next to the history information. The reported history matrix now has 4 rows rather than 2, where the extra rows represents the timestamp of each function entry/exit:<br />
<span id="more-3158"></span></p>
<pre lang='matlab'>
>> profile('on','-timestamp'); surf(peaks); profile('off')
>> profData = profile('info');
>> profData.FunctionHistory(:,1:3)
ans =
                0                0                1
                1                2                2
       1347473710       1347473710       1347473710
           453000           453000           468000
</pre>
<p>In this report, the 3rd row represents the timestamp in seconds, while the 4th row represents the fractional portion of the timestamp, in microseconds. In the example above, the first timestamp item corresponds to 1347473710.453 seconds.<br />
The seconds value appears to be related to the number of seconds since midnight Jan 1, 1970 (so-called <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Unix_time"><i>Epoch</i></a>), which is a standard time representation in computing systems. However, the actual value appears to be off by slightly over a day from the expected value (which is retrievable via <code>getTime(java.util.Date)</code>) for some unknown reason. Since we are only interested in <i>relative</i>, rather than <i>absolute</i> times when profiling, this minor difference does not affect us.<br />
The timeline of the profiling session can be visualized as follows:</p>
<pre lang='matlab'>
histData = profData.FunctionHistory;
startTime     = histData(3,1) + histData(4,1)/1e6;
relativeTimes = histData(3,:) + histData(4,:)/1e6 - startTime;
plot(relativeTimes);
</pre>
<p><center><figure style="width: 494px" class="wp-caption aligncenter"><img decoding="async" alt="Profiling history timeline" src="https://undocumentedmatlab.com/images/Profiler2.png" title="Profiling history timeline" width="494" height="385" /><figcaption class="wp-caption-text">Profiling history timeline</figcaption></figure></center><br />
This report helps us see that a particular set of function calls, around the 100th call mark, is responsible for about 0.5 seconds, a prime candidate for tuning investigation. If we only relied on the standard profiling report we might have missed this because it might have been meshed into the same &#8220;bucket&#8221; as other invocations of the same function. As illustration, take the following simulated example:</p>
<pre lang='matlab'>
Invocation  #1 of func():  0.500 secs
Invocation  #2 of func():  0.013 secs
Invocation  #3 of func():  0.011 secs
   ...
Invocation #10 of func():  0.012 secs
_____________________________________
Total invocation time:     0.600 secs
</pre>
<p>In this simulation, we would not have known that the 0.6 secs invocation time of <i>func()</i> is not really evenly distributed across all 10 invocations, and this would lead us to incorrect conclusions. For example, we could spend time unnecessarily on tuning the steady-state run-time performance of the function, whereas we should really have concentrated on only the first invocation. By looking at the actual timestamps we could see the large run-time used by the first invocation and this information can possibly be used to tune this first invocation and significantly reduce the overall time taken by the function.<br />
Note: instead of using <i><b>profile -timestamp</b></i>, we could also have used the undocumented built-in function <i><b>callstats</b></i>, which is the underlying profiling engine (the <i><b>profile</b></i> function is simply a convenient wrapper function to <i><b>callstats</b></i> – take a look within <i>profile.m</i>):</p>
<pre lang='matlab'>callstats('history',2);  % 0 = -nohistory, 1 = -history, 2 = -timestamp</pre>
<p>History collection has an overhead, so if you don&#8217;t need it then you should turn it off:</p>
<pre lang='matlab'>
profile -nohistory
profile('-nohistory')    % equivalent alternative
callstats('history',0);  % equivalent alternative
</pre>
<p><b><u>Addendum</u> (June 16th, 2014):</b> I have created a utility (<code>profile_history</code>, available on the <a href="http://www.mathworks.com/matlabcentral/fileexchange/46976-profile-history-display-graphical-profiling-timline-data" rel="nofollow" target="_blank">Matlab File Exchange</a>) that parses all this profile data and presents it in an interactive GUI. See <a href="/articles/function-call-timeline-profiling" target="_blank">this article</a> for details.<br />
<center><a target="_blank" href="/images/profile_history.png"><img decoding="async" alt="Function call timeline profiling (click for full-size image)" src="https://undocumentedmatlab.com/images/profile_history.png" title="Function call timeline profiling (click for full-size image)" width="100%" style="max-width: 658px;" /></a><br />
Function call timeline profiling (click for full-size image)</center></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-3">Undocumented Profiler options part 3</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4" rel="bookmark" title="Undocumented Profiler options part 4">Undocumented Profiler options part 4 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 4 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options" rel="bookmark" title="Undocumented profiler options">Undocumented profiler options </a> <small>The Matlab profiler has some undocumented options that facilitate debugging memory bottlenecks and JIT (Just-In-Time Java compilation) problems....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-2" rel="bookmark" title="Undocumented Profiler options part 2">Undocumented Profiler options part 2 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 2 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/buggy-profiler-option" rel="bookmark" title="Buggy Profiler option">Buggy Profiler option </a> <small>a bug exists in the profiler that prevents usage of its documented CPU timing functionality. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-3/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Undocumented Profiler options part 2</title>
		<link>https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=undocumented-profiler-options-part-2</link>
					<comments>https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-2#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 19 Sep 2012 18:00:42 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Profiler]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3148</guid>

					<description><![CDATA[<p>Several undocumented features of the Matlab Profiler can make it much more useful - part 2 of series. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-2">Undocumented Profiler options part 2</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options" rel="bookmark" title="Undocumented profiler options">Undocumented profiler options </a> <small>The Matlab profiler has some undocumented options that facilitate debugging memory bottlenecks and JIT (Just-In-Time Java compilation) problems....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4" rel="bookmark" title="Undocumented Profiler options part 4">Undocumented Profiler options part 4 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 4 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-3" rel="bookmark" title="Undocumented Profiler options part 3">Undocumented Profiler options part 3 </a> <small>An undocumented feature of the Matlab Profiler can report call history timeline - part 3 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/buggy-profiler-option" rel="bookmark" title="Buggy Profiler option">Buggy Profiler option </a> <small>a bug exists in the profiler that prevents usage of its documented CPU timing functionality. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Three years ago I published an <a target="_blank" href="/articles/undocumented-profiler-options/">article</a> on undocumented profiler options. Since then, I&#8217;ve posted several articles about performance tuning and profiling (for example, <a target="_blank" href="/articles/profiling-matlab-memory-usage/">memory profiling</a>) but nothing specifically about the Profiler. There are several additional undocumented aspects of the Profiler that I&#8217;d like to expose. Today&#8217;s article will focus on benefits that require a bit of tweaking to Matlab files (fixing a font issue and increasing the reported time resolution). Next week&#8217;s article will explain undocumented switches of the <i><b>profile</b></i> function, which can be used to profile built-in functions, as well as to provide detailed history timeline of the function calls.</p>
<h3 id="font">Fixing a Profiler font problem</h3>
<p>On my system, starting in R2012a, the code lines in the detailed profiling report look awful. The reason is that they are rendered using a proportional font, rather than the monospaced (fixed-width) font that is specified in the Matlab Preferences and used everywhere else (the Editor, Command Window etc.):<br />
<center><figure style="width: 300px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Before: ugly (proportional-font) profiling report" src="https://undocumentedmatlab.com/images/Profiler5.png" title="Before: ugly (proportional-font) profiling report" width="235" height="225" /><figcaption class="wp-caption-text">Before: ugly (proportional-font) profiling report</figcaption></figure></center><br />
<span id="more-3148"></span><br />
I have seen this phenomenon on several of my clients&#8217; systems, so I&#8217;m pretty sure that this is not an isolated issue. However, I do not know whether this problem is wide-spread.<br />
In any case, the solution is very simple: Edit the <i>%matlabroot%/toolbox/matlab/codetools/matlab-report-styles.css</i> files and replace the following CSS directives near the top of the file:</p>
<pre lang='css'>
PRE {
  font-size: 100%;
}
</pre>
<p>with this one:</p>
<pre lang='css'>
pre, tt {
  font-family: monospace
  font-size: 100%;
}
</pre>
<p><center><figure style="width: 370px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="After: monospaced profiling report" src="https://undocumentedmatlab.com/images/Profiler6.png" title="After: monospaced profiling report" width="370" height="225" /><figcaption class="wp-caption-text">After: monospaced profiling report<br />(note the 1-millisecond timing resolution)</figcaption></figure></center><br />
A very similar problem seems to afflict the Help browser. I could not add the CSS fix there because the help pages use the <i>docstyle.css</i> files that are bundled within the <i>\help\techdoc\help.jar</i> file. If you wish, you could update them there (a JAR is a simple zip file after all).<br />
You may perhaps recall my related <a target="_blank" href="/articles/multi-line-tooltips/">article</a> last year, where I showed how to convert a proportional-font multi-line tooltip into a nicely-formatted monospaced tooltip.</p>
<h3 id="resolution">Increasing the reported timing resolution</h3>
<p>The Profiler records information at a system-dependent time resolution, typically 1 millisecond. However, the profiling report only displays information at a granularity of 10 ms. I often find it useful to increase the reported resolution to 1 ms, and in fact the screenshots above reflect this change. This can easily be done by editing the <i><b>profview</b></i> function (<i>%matlabroot%/toolbox/matlab/codetools/profview.m</i>. This function can be edited in the MATLAB editor via <i><b>edit</b>(&#8216;profview&#8217;)</i>).<br />
The following is from lines 1410-1418 of <i>profview.m</i> in R2012a:</p>
<pre lang='matlab'>
% Display the time
if timePerLine > 0.01,
    s{end+1} = sprintf('<span style="color: #FF0000"> %5.2f </span>',...
        timePerLine);
elseif timePerLine > 0
    s{end+1} = '<span style="color: #FF0000">&lt; 0.01 </span>';
else
    s{end+1} = '       ';
end
</pre>
<p>which could be replaced by the following (modified lines highlighted):</p>
<pre lang='matlab' highlight="1,2,5">
if timePerLine >= 0.005,
    s{end+1} = sprintf('<span style="color: #FF0000"> %6.3f</span>',...
        timePerLine);
elseif timePerLine > 0
    s{end+1} = '<span style="color: #FF0000">&lt; 0.005</span>';
else
    s{end+1} = '       ';
end
</pre>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-2">Undocumented Profiler options part 2</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options" rel="bookmark" title="Undocumented profiler options">Undocumented profiler options </a> <small>The Matlab profiler has some undocumented options that facilitate debugging memory bottlenecks and JIT (Just-In-Time Java compilation) problems....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4" rel="bookmark" title="Undocumented Profiler options part 4">Undocumented Profiler options part 4 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 4 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-3" rel="bookmark" title="Undocumented Profiler options part 3">Undocumented Profiler options part 3 </a> <small>An undocumented feature of the Matlab Profiler can report call history timeline - part 3 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/buggy-profiler-option" rel="bookmark" title="Buggy Profiler option">Buggy Profiler option </a> <small>a bug exists in the profiler that prevents usage of its documented CPU timing functionality. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-2/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Profiling Matlab memory usage</title>
		<link>https://undocumentedmatlab.com/articles/profiling-matlab-memory-usage?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=profiling-matlab-memory-usage</link>
					<comments>https://undocumentedmatlab.com/articles/profiling-matlab-memory-usage#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 01 Mar 2012 00:13:04 +0000</pubDate>
				<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Memory]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Profiler]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2768</guid>

					<description><![CDATA[<p>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/profiling-matlab-memory-usage">Profiling Matlab memory usage</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/internal-matlab-memory-optimizations" rel="bookmark" title="Internal Matlab memory optimizations">Internal Matlab memory optimizations </a> <small>Copy-on-write and in-place data manipulations are very useful Matlab performance improvement techniques. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlabs-internal-memory-representation" rel="bookmark" title="Matlab&#039;s internal memory representation">Matlab&#039;s internal memory representation </a> <small>Matlab's internal memory structure is explored and discussed. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-java-memory-leaks-performance" rel="bookmark" title="Matlab-Java memory leaks, performance">Matlab-Java memory leaks, performance </a> <small>Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/function-call-timeline-profiling" rel="bookmark" title="Function call timeline profiling">Function call timeline profiling </a> <small>A new utility enables to interactively explore Matlab function call timeline profiling. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Anyone who has had experience with real-life applications knows that Memory usage can have a significant impact on the application&#8217;s usability, in aspects such as performance, interactivity, and even (on some lousy memory-management Operating Systems) crashes/hangs.<br />
In Matlab releases of the past few years, this has been addressed by expanding the information reported by the built-in <i><b>memory</b></i> function. In addition, an undocumented feature was added to the Matlab Profiler that <a target="_blank" href="/articles/undocumented-profiler-options/">enables monitoring</a> memory usage.<br />
<center><figure style="width: 450px" class="wp-caption aligncenter"><br />
<img decoding="async" title="Profile report with memory &amp; JIT info" src="https://undocumentedmatlab.com/images/profile2d_450.png" alt="Profile report with memory &amp; JIT info" width="450" /><img decoding="async" title="Profile report with memory &amp; JIT info" src="https://undocumentedmatlab.com/images/profile2c_450.png" alt="Profile report with memory &amp; JIT info" width="450" /><br />
<img decoding="async" title="Profile report with memory &amp; JIT info" src="https://undocumentedmatlab.com/images/profile2.png" alt="Profile report with memory &amp; JIT info" width="416" /><br />
<figcaption class="wp-caption-text">Profile report with memory &amp; JIT info</figcaption></figure></center><br />
In Matlab release R2008a (but not on newer releases) we could also use a nifty parameter of the undocumented <a target="_blank" href="/articles/undocumented-feature-function/"><i><b>feature</b></i> function</a>:</p>
<pre lang='matlab'>
>> feature mtic; a=ones(100); feature mtoc
ans =
      TotalAllocated: 84216
          TotalFreed: 2584
    LargestAllocated: 80000
           NumAllocs: 56
            NumFrees: 43
                Peak: 81640
</pre>
<p>As can easily be seen in this example, allocating 100<sup>2</sup> doubles requires 80000 bytes of allocation, plus some 4KB others that were allocated (and 2KB freed) within the function <i><b>ones</b></i>. Running the same code line again gives a very similar result, but now there are 80000 more bytes freed when the matrix <code>a</code> is overwritten:</p>
<pre lang='matlab'>
>> feature mtic; a=ones(100); feature mtoc
ans =
      TotalAllocated: 84120
          TotalFreed: 82760
    LargestAllocated: 80000
           NumAllocs: 54
            NumFrees: 49
                Peak: 81328
</pre>
<p>This is pretty informative and very handy for debugging memory bottlenecks. Unfortunately, starting in R2008b, features mtic and mtoc are no longer supported <i>&#8220;under the current <a target="_blank" rel="nofollow" href="http://www.mathworks.com/support/tech-notes/1100/1106.html">memory manager</a>&#8220;</i>. Sometime around 2010 the mtic and mtoc features were completely removed. Users of R2008b and newer releases therefore need to use the internal structs returned by the <i><b>memory</b></i> function, and/or use the profiler&#8217;s memory-monitoring feature. If you ask me, using mtic/mtoc was much simpler and easier. I for one miss these features.<br />
<span id="Java"></span><br />
In a related matter, if we wish to monitor Java&#8217;s memory used within Matlab, we are in a bind, because there are no built-in tools to help us. there are several JVM switches that can be turned on in the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/support/solutions/en/data/1-18I2C/"><i>java.opts</i></a> file: -Xrunhprof[:help]|[:option=value,&#8230;], -Xprof, -Xrunprof, -XX:+PrintClassHistogram <a target="_blank" rel="nofollow" href="http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html">and so on</a>. There are several memory-monitoring (so-called &#8220;heap-walking&#8221;) tools: the standard JDK jconsole, jmap, jhat and jvisualvm (with its useful plugins) provide good basic coverage. MathWorks has <a target="_blank" rel="nofollow" href="http://www.mathworks.com/support/solutions/en/data/1-3L4JU7/">posted</a> a tutorial on using jconsole with Matlab. There are a number of other third-party tools such as <a target="_blank" rel="nofollow" href="http://www.khelekore.org/jmp/">JMP</a> (for JVMs 1.5 and earlier) or <a target="_blank" rel="nofollow" href="http://www.khelekore.org/jmp/tijmp/">TIJMP</a> (for JVM 1.6). Within Matlab, we can use utilities such as <a target="_blank" rel="nofollow" href="http://www.javamex.com/classmexer/">Classmexer</a> to estimate a particular object&#8217;s size (both shallow and deep referencing), or use <code>java.lang.Runtime.getRuntime()</code>&#8216;s methods (<i>maxMemory(), freeMemory()</i> and <i>totalMemory()</i>) to monitor overall Java memory (<a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/296813#797410">sample usage</a>).<br />
We can monitor the Java memory (which is part of the overall Matlab process memory) usage using Java&#8217;s built-in <a target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Runtime.html"><code>Runtime</code></a> class:</p>
<pre lang='matlab'>
>> r=java.lang.Runtime.getRuntime
r =
java.lang.Runtime@5fb3b54
>> r.freeMemory
ans =
    86147768
>> r.totalMemory
ans =
   268304384
>> usedMemory = r.totalMemory - r.freeMemory;
</pre>
<p>Specifically in R2011b (but in no other release), we can also use a built-in Java memory monitor. Unfortunately, this simple and yet useful memory monitor was removed in R2012a (or maybe it was just moved to another package and I haven&#8217;t found out where&#8230; <i>yet</i>&#8230;):</p>
<pre lang='matlab'>
com.mathworks.xwidgets.JavaMemoryMonitor.invoke
</pre>
<p><center><figure style="width: 220px" class="wp-caption aligncenter"><img decoding="async" alt="Matlab R2011b's Java memory monitor" src="https://undocumentedmatlab.com/images/Java_Memory_Monitor.png" title="Matlab R2011b's Java memory monitor" width="159" /><figcaption class="wp-caption-text">Matlab R2011b's Java memory monitor</figcaption></figure></center><br />
As I have already noted quite often, using undocumented Matlab features and functions carries the risk that they will not be supported in some future Matlab release. Today&#8217;s article is a case in point.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/profiling-matlab-memory-usage">Profiling Matlab memory usage</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/internal-matlab-memory-optimizations" rel="bookmark" title="Internal Matlab memory optimizations">Internal Matlab memory optimizations </a> <small>Copy-on-write and in-place data manipulations are very useful Matlab performance improvement techniques. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlabs-internal-memory-representation" rel="bookmark" title="Matlab&#039;s internal memory representation">Matlab&#039;s internal memory representation </a> <small>Matlab's internal memory structure is explored and discussed. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-java-memory-leaks-performance" rel="bookmark" title="Matlab-Java memory leaks, performance">Matlab-Java memory leaks, performance </a> <small>Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/function-call-timeline-profiling" rel="bookmark" title="Function call timeline profiling">Function call timeline profiling </a> <small>A new utility enables to interactively explore Matlab function call timeline profiling. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/profiling-matlab-memory-usage/feed</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Datenum performance</title>
		<link>https://undocumentedmatlab.com/articles/datenum-performance?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=datenum-performance</link>
					<comments>https://undocumentedmatlab.com/articles/datenum-performance#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 04 May 2011 18:00:34 +0000</pubDate>
				<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[datenum]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Profiler]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2299</guid>

					<description><![CDATA[<p>The performance of the built-in Matlab function datenum can be significantly improved by using an undocumented internal help function</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/datenum-performance">Datenum performance</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/performance-scatter-vs-line" rel="bookmark" title="Performance: scatter vs. line">Performance: scatter vs. line </a> <small>In many circumstances, the line function can generate visually-identical plots as the scatter function, much faster...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/improving-save-performance" rel="bookmark" title="Improving save performance">Improving save performance </a> <small>There are many different ways of improving Matlab's standard save function performance. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-performance" rel="bookmark" title="Plot performance">Plot performance </a> <small>Undocumented inner plot mechanisms can significantly improve plotting performance ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A few days ago, a reader on StackOverflow <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/5818583/faster-function-than-datenum-in-matlab">asked</a> whether it is possible to improve the performance of Matlab&#8217;s built-in <i><b>datenum</b></i> function. This question reminded me of a similar case that I answered exactly two years ago, of <a target="_blank" href="/articles/ismembc-undocumented-helper-function/">improving the performance of the built-in <i><b>ismember</b></i> function</a>.<br />
In both cases, the solution to the performance question can be found by simply using Matlab&#8217;s built-in profiler in order to extract just the core processing functionality. It is often found that in a particular situation there is no need for all the input arguments data validity checks, and under some known limitations we can indeed use the core functionality directly.<br />
In the case of <i><b>ismember</b></i>, it turned out that if we are assured in advance that the input data are sorted non-sparse non-NaN values, then we can use the undocumented built-in helper functions <i><b>ismembc</b></i> or <i><b>ismembc2</b></i> for much-improved performance over the standard <i><b>ismember</b></i>. Both <i><b>ismembc</b></i> and <i><b>ismembc2</b></i> happen to be mex files, although this is not always the case for helper functions.<br />
Our <i><b>datenum</b></i> case is very similar. It turns out that <i><b>datenum</b></i> uses the undocumented built-in helper function <i><b>dtstr2dtnummx</b></i> for the actual processing &#8211; converting a date from text to floating-point number. As I noted in <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/5818583/faster-function-than-datenum-in-matlab/5823278#5823278">my response</a> to the StackOverflow question, we can directly use this helper function for improved performance: On my particular computer, <i><b>dtstr2dtnummx</b></i> is over 3 times faster than the standard <i><b>datenum</b></i> function:</p>
<pre lang='matlab'>
% Fast - using dtstr2dtnummx
>> tic, for i=1:1000; dateNum=dtstr2dtnummx({'2010-12-12 12:21:12.123'},'yyyy-MM-dd HH:mm:ss'); end; dateNum,toc
dateNum =
          734484.514722222
Elapsed time is 0.218423 seconds.
% Slower - using datenum
>> tic, for i=1:1000; dateNum=datenum({'2010-12-12 12:21:12.123'},'yyyy-mm-dd HH:MM:SS'); end; dateNum,toc
dateNum =
          734484.514722222   % Same value as dtstr2dtnummx - good!
Elapsed time is 0.658352 seconds.   % 3x slower than dtstr2dtnummx - bad!
</pre>
<p>While the difference in timing may appear negligible, if you are using this function to parse a text file with thousands of lines, each with its own timestamp, then these seemingly negligible time differences quickly add up. Of course, this only makes sense to do if you find out (using the profiler again) that this date parsing is a performance hotspot in your particular application. It was indeed such a performance hotspot in one of my applications, as it apparently was also for the original poster on StackOverflow.<br />
Like <i><b>ismembc</b></i>, <i><b>dtstr2dtnummx</b></i> is an internal mex function. On my Windows system it is located in C:\Program Files\Matlab\R2011a\toolbox\matlab\timefun\private\dtstr2dtnummx.mexw32. It will have a different extension non-Windows systems, but you will easily find it in its containing folder.<br />
To gain access to <i><b>dtstr2dtnummx</b></i>, simply add its folder to the Matlab path using the <i><b>addpath</b></i> function, or copy the dtstr2dtnummx.mexw32 file to another folder that is already on your Matlab path.<br />
Note that the string format is different between <i><b>dtstr2dtnummx</b></i> and <i><b>datenum</b></i>: In the test case above, <i><b>dtstr2dtnummx</b></i> used <code>'yyyy-MM-dd HH:mm:ss'</code>, while <i><b>datenum</b></i> required <code>'yyyy-<b>mm</b>-dd HH:<b>MM:SS</b>'</code>. I have no idea why MathWorks did not keep consistent formatting strings. But because of this, we need to be extra careful (<a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/5831563/matlab-date-format/">example1</a>, <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/5880242/matlab-datenum-generation">example2</a>). If you are interested in finding out how the <i><b>datenum</b></i> format strings translates into a <i><b>dtstr2dtnummx</b></i>, take a look at the helper function <i><b>cnv2icudf</b></i>, which is a very readable m-file located in the same folder as <i><b>dtstr2dtnummx</b></i>.<br />
To those interested, the folder that contains <i><b>dtstr2dtnummx</b></i> also contains some other interesting date conversion functions, so explore and enjoy!<br />
Perhaps the main lesson that can be learned from this article, and its <i><b>ismembc</b></i> predecessor of two years ago, is that it is very useful to profile the code for performance hotspots. When such a hotspot is found, don&#8217;t stop your profiling at the built-in Matlab functions &#8211; keep digging in the profiler results and perhaps you&#8217;ll find that you can improve performance by taking an internal shortcut.<br />
Have you discovered any other performance shortcuts in a built-in Matlab function? If so, please <a href="/articles/datenum-performance/#respond">post a comment</a> to tell us all about it.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/datenum-performance">Datenum performance</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/performance-scatter-vs-line" rel="bookmark" title="Performance: scatter vs. line">Performance: scatter vs. line </a> <small>In many circumstances, the line function can generate visually-identical plots as the scatter function, much faster...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/improving-save-performance" rel="bookmark" title="Improving save performance">Improving save performance </a> <small>There are many different ways of improving Matlab's standard save function performance. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-performance" rel="bookmark" title="Plot performance">Plot performance </a> <small>Undocumented inner plot mechanisms can significantly improve plotting performance ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/datenum-performance/feed</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
			</item>
		<item>
		<title>Plot performance</title>
		<link>https://undocumentedmatlab.com/articles/plot-performance?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=plot-performance</link>
					<comments>https://undocumentedmatlab.com/articles/plot-performance#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 16 Jun 2010 09:55:47 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Profiler]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Undocumented property]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=1623</guid>

					<description><![CDATA[<p>Undocumented inner plot mechanisms can significantly improve plotting performance </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/plot-performance">Plot performance</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/performance-scatter-vs-line" rel="bookmark" title="Performance: scatter vs. line">Performance: scatter vs. line </a> <small>In many circumstances, the line function can generate visually-identical plots as the scatter function, much faster...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-liminclude-properties" rel="bookmark" title="Plot LimInclude properties">Plot LimInclude properties </a> <small>The plot objects' XLimInclude, YLimInclude, ZLimInclude, ALimInclude and CLimInclude properties are an important feature, that has both functional and performance implications....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/bar-plot-customizations" rel="bookmark" title="Bar plot customizations">Bar plot customizations </a> <small>Matlab bar charts can be customized in various nifty ways. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>I recently consulted to a client who wanted to display an interactive plot with numerous data points that kept updating in real-time. Matlab&#8217;s standard plotting functions simply could not keep up with the rate of data change. Today, I want to share a couple of very simple undocumented hacks that significantly improve plotting performance and fixed my problem.<br />
I begin by stating the obvious: whenever possible, try to <a target="_blank" rel="nofollow" href="http://www.mathworks.com/support/tech-notes/1100/1109.html">vectorize</a> your code, <a target="_blank" rel="nofollow" href="http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/f8-784135.html">preallocate the data</a> and other <a target="_blank" rel="nofollow" href="http://www.mathworks.com/support/solutions/en/data/1-15NM7/">performance-improving techniques suggested by Matlab</a>. Unfortunately, sometimes (as in my specific case above) all these cannot help. Even in such cases, we can still find important performance tricks, such as these:</p>
<h3 id="limits">Performance hack #1: manual limits</h3>
<p>Whenever Matlab updates plot data, it checks whether any modification needs to be done to any of its limits. This computation-intensive task is done for any limit that is set to &#8216;Auto&#8217; mode, which is the default axes limits mode. If instead we manually set the axes limits to the requested range, Matlab skips these checks, enabling much faster plotting performance.<br />
Let us simulate the situation by adding 500 data points to a plot, one at a time:</p>
<pre lang="matlab">
>> x=0:0.02:10; y=sin(x);
>> clf; cla; tic;
>> drawnow; plot(x(1),y(1)); hold on; legend data;
>> for idx = 1 : length(x); plot(x(idx),y(idx)); drawnow; end;
>> toc
Elapsed time is 21.583668 seconds.
</pre>
<p><center><figure style="width: 311px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="simple plot with 500 data points" src="https://undocumentedmatlab.com/images/Plot.png" title="simple plot with 500 data points" width="311" height="286" /><figcaption class="wp-caption-text">simple plot with 500 data points</figcaption></figure></center><br />
And now let&#8217;s use static axes limits:</p>
<pre lang="matlab">
>> x=0:0.02:10; y=sin(x);
>> clf; cla; tic; drawnow;
>> plot(x(1),y(1)); hold on; legend data;
>> xlim([0,10]); ylim([-1,1]);  % static limits
>> for idx = 1 : length(x); plot(x(idx),y(idx)); drawnow; end;
>> toc
Elapsed time is 16.863090 seconds.
</pre>
<p>Note that this trick is the basis for the performance improvement that occurs when using the plot&#8217;s <a target="_blank" href="/articles/plot-liminclude-properties/">undocumented set of <b>LimInclude</b> properties</a>.<br />
Of course, setting manual limits prevents the axes limits from growing and shrinking automatically with the data, which can actually be a very useful feature sometimes. But if performance is important, we now know that we have this tool to improve it.</p>
<h3 id="Legend">Performance hack #2: static legend</h3>
<p>Hack #1 gave us a 22% performance boost, but we can do much better. Running the <a target="_blank" href="/articles/undocumented-profiler-options/">profiler</a> on the code above we see that much of the time is spent recomputing the legend. Looking inside the legend code (specifically, the <i><b>legendcolorbarlayout</b></i> function), we detect several short-circuits that we can use to make the legend static and prevent recomputation:</p>
<pre lang="matlab">
>> x=0:0.02:10; y=sin(x);
>> clf; cla; tic; drawnow;
>> plot(x(1),y(1)); hold on; legend data;
>> xlim([0,10]); ylim([-1,1]);  % static limits
>> % Static legend
>> set(gca,'LegendColorbarListeners',[]);
>> setappdata(gca,'LegendColorbarManualSpace',1);
>> setappdata(gca,'LegendColorbarReclaimSpace',1);
>> for idx = 1 : length(x); plot(x(idx),y(idx)); drawnow; end;
>> toc
Elapsed time is 5.209053 seconds.
</pre>
<p>Now this is much much better &#8211; a 76% performance boost compared to the original plot (i.e., 4 times faster!). Of course, it prevents the legend from being dynamically updated. Sometimes we actually wish for this dynamic effect (last year I explained how to use the <a target="_blank" href="/articles/legend-semi-documented-feature/">legend&#8217;s undocumented -DynamicLegend feature</a> for even greater dynamic control). But when performance is important, we can still display a legend without its usual performance cost.<br />
In conclusion, I have demonstrated that Matlab performance can often be improved significantly, even in the absence of any vectorization, by simply understanding the internal mechanisms and bypassing those which are irrelevant in our specific case.<br />
Have you found other similar performance hacks? If so, please share them in the <a href="#respond">comments section</a> below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/plot-performance">Plot performance</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/performance-scatter-vs-line" rel="bookmark" title="Performance: scatter vs. line">Performance: scatter vs. line </a> <small>In many circumstances, the line function can generate visually-identical plots as the scatter function, much faster...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-liminclude-properties" rel="bookmark" title="Plot LimInclude properties">Plot LimInclude properties </a> <small>The plot objects' XLimInclude, YLimInclude, ZLimInclude, ALimInclude and CLimInclude properties are an important feature, that has both functional and performance implications....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/bar-plot-customizations" rel="bookmark" title="Bar plot customizations">Bar plot customizations </a> <small>Matlab bar charts can be customized in various nifty ways. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/plot-performance/feed</wfw:commentRss>
			<slash:comments>36</slash:comments>
		
		
			</item>
		<item>
		<title>Undocumented profiler options</title>
		<link>https://undocumentedmatlab.com/articles/undocumented-profiler-options?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=undocumented-profiler-options</link>
					<comments>https://undocumentedmatlab.com/articles/undocumented-profiler-options#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 02 Apr 2009 22:24:25 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Memory]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[callstats]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Profiler]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=143</guid>

					<description><![CDATA[<p>The Matlab profiler has some undocumented options that facilitate debugging memory bottlenecks and JIT (Just-In-Time Java compilation) problems.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-profiler-options">Undocumented profiler options</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-3" rel="bookmark" title="Undocumented Profiler options part 3">Undocumented Profiler options part 3 </a> <small>An undocumented feature of the Matlab Profiler can report call history timeline - part 3 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-2" rel="bookmark" title="Undocumented Profiler options part 2">Undocumented Profiler options part 2 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 2 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4" rel="bookmark" title="Undocumented Profiler options part 4">Undocumented Profiler options part 4 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 4 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/buggy-profiler-option" rel="bookmark" title="Buggy Profiler option">Buggy Profiler option </a> <small>a bug exists in the profiler that prevents usage of its documented CPU timing functionality. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>The Matlab profiler is a powerful tool for debugging performance-related issues in Matlab applications. However, it also has some undocumented options that facilitate other forms of debugging, namely memory bottlenecks and JIT (Just-In-Time compilation) problems.<br />
To turn on memory stats in the profile report, run this (only once is necessary &#8211; will be remembered for future profiling runs):</p>
<blockquote>
<pre>profile -memory on;
profile(<span style="color: #800080;">'-memory','on'</span>);  <span style="color: #008000;">% an alternative</span></pre>
</blockquote>
<p>To turn on JIT information, run this (again, only once is necessary, prior to profile report):</p>
<blockquote>
<pre>setpref(<span style="color: #800080;">'profiler','showJitLines'</span>,1);</pre>
</blockquote>
<p>You will then see additional JIT and memory (allocated, freed and peak) information displayed in the profile report, as well as the options to sort by allocated, freed and peak memory:<br />
<figure style="width: 450px" class="wp-caption aligncenter"><br />
<img decoding="async" title="Profile report with memory &amp; JIT info" src="https://undocumentedmatlab.com/images/profile2d_450.png" alt="Profile report with memory &amp; JIT info" width="450" /><img decoding="async" title="Profile report with memory &amp; JIT info" src="https://undocumentedmatlab.com/images/profile2c_450.png" alt="Profile report with memory &amp; JIT info" width="450" /><br />
<img decoding="async" title="Profile report with memory &amp; JIT info" src="https://undocumentedmatlab.com/images/profile2.png" alt="Profile report with memory &amp; JIT info" width="416" /><br />
<figcaption class="wp-caption-text">Profile report with memory &amp; JIT info</figcaption></figure><br />
For those interested, the references to these two options appear within the code of profview.m (line 1199 on R2007b), for the JIT option:</p>
<blockquote>
<pre>showJitLines = getpref(<span style="color: #800080;">'profiler','showJitLines'</span>,false);</pre>
</blockquote>
<p>&#8230;and profile.m (lines 163-165 on R2007b), for the memory option:</p>
<blockquote>
<pre><span style="color: #0000ff;">if</span> memory ~= -1
    callstats(<span style="color: #800080;">'memory'</span>, memory);
<span style="color: #0000ff;">end</span></pre>
</blockquote>
<p>Note that there appears to be two undocumented additional memory-related options in profile.m (lines 311-312):</p>
<blockquote>
<pre>options = {<span style="color: #800080;">'detail', 'timer', 'history', 'nohistory', 'historysize'</span>, ...
           <span style="color: #800080;">'timestamp', 'memory', 'callmemory', 'nomemory'</span> };</pre>
</blockquote>
<p>However, &#8216;-nomemory&#8217; appears to simply turn the memory stats collection off, and &#8216;-callmemory&#8217; is not recognized because of a bug in line 349, which looks for &#8216;call<strong>no</strong>memory&#8217;&#8230;:</p>
<blockquote>
<pre>    <span style="color: #0000ff;">case </span><span style="color: #800080;">'callnomemory'</span>   <span style="color: #008000;">% should be 'callmemory'</span>
           memory = 2;</pre>
</blockquote>
<p>When this bug is fixed, we see that we get only partial memory information, so the &#8216;-callmemory&#8217; option is really not useful &#8211; use &#8216;-memory&#8217; instead.<br />
<b><u>Addendum (Jan 31, 2011):</u> JIT information has been removed in Matlab 7.12 (R2011a). I assume that this was done so that programmers will not attempt to depend on JITC functionality in their code (see <a href="/articles/undocumented-profiler-options/#comment-64">Michelle Hirsch&#8217;s comment</a> below). It&#8217;s a good thing that the memory options remain, since these are quite useful in profiling memory-related bottlenecks.</b></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-profiler-options">Undocumented profiler options</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-3" rel="bookmark" title="Undocumented Profiler options part 3">Undocumented Profiler options part 3 </a> <small>An undocumented feature of the Matlab Profiler can report call history timeline - part 3 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-2" rel="bookmark" title="Undocumented Profiler options part 2">Undocumented Profiler options part 2 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 2 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4" rel="bookmark" title="Undocumented Profiler options part 4">Undocumented Profiler options part 4 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 4 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/buggy-profiler-option" rel="bookmark" title="Buggy Profiler option">Buggy Profiler option </a> <small>a bug exists in the profiler that prevents usage of its documented CPU timing functionality. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/undocumented-profiler-options/feed</wfw:commentRss>
			<slash:comments>23</slash:comments>
		
		
			</item>
	</channel>
</rss>
