<?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>Hanan Kavitz &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/hanan-kavitz/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Thu, 16 Jan 2025 15:33:04 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.3</generator>
	<item>
		<title>Matlab compilation quirks &#8211; take 2</title>
		<link>https://undocumentedmatlab.com/articles/matlab-compilation-quirks-take-2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-compilation-quirks-take-2</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-compilation-quirks-take-2#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 31 May 2017 18:00:42 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Toolbox]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Compiler]]></category>
		<category><![CDATA[Hanan Kavitz]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6919</guid>

					<description><![CDATA[<p>A few hard-to-trace quirks with Matlab compiler outputs are explained. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-compilation-quirks-take-2">Matlab compilation quirks &#8211; take 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/quirks-with-compiled-matlab-dlls" rel="bookmark" title="Quirks with compiled Matlab DLLs">Quirks with compiled Matlab DLLs </a> <small>Several quirks with Matlab-compiled DLLs are discussed and workarounds suggested. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/quirks-with-parfor-vs-for" rel="bookmark" title="Quirks with parfor vs. for">Quirks with parfor vs. for </a> <small>Parallelizing loops with Matlab's parfor might generate unexpected results. Users beware! ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/secure-ssl-connection-between-matlab-and-postgresql" rel="bookmark" title="Secure SSL connection between Matlab and PostgreSQL">Secure SSL connection between Matlab and PostgreSQL </a> <small>It is tricky, but quite possible, to use SSL to connect Matlab to a PostgreSQL database. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-infiniband-with-matlab-parallel-computing-toolbox" rel="bookmark" title="Using Infiniband with Matlab Parallel Computing Toolbox">Using Infiniband with Matlab Parallel Computing Toolbox </a> <small>Infiniband networking can significantly improve PCT performance in Matlab parallelization and distributed computing. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again I would like to welcome guest blogger <a href="https://www.mathworks.com/matlabcentral/profile/authors/2392999-hanan-kavitz" rel="nofollow" target="_blank">Hanan Kavitz</a> of <a href="http://www.appliedmaterials.com" rel="nofollow" target="_blank">Applied Materials</a>. Hanan posted a couple of guest posts here over the past few years, including a post last year about <a href="/articles/quirks-with-compiled-matlab-dlls" target="_blank">quirks with Matlab-compiled DLLs</a>. Today Hanan will follow up on that post by discussing several additional quirks that they have encountered with Matlab compilations/deployment.</i></p>
<h3 id="make"><i>Don&#8217;t fix it, if it ain&#8217;t broke&#8230;</i></h3>
<p>In Applied Materials Israel (PDC) we use Matlab code for both algorithm development and deployment (production). As part of the dev-ops build system, which builds our product software versions, we build Matlab artifacts (binaries) from the Matlab source code.<br />
A typical software version has several hundreds Matlab artifacts that are automatically rebuilt on a daily basis, and we have many such versions – totaling many thousands of compilations each day.<br />
This process takes a long time, so we were looking for a way to make it more efficient.<br />
The idea that we chose to implement sounds simple – take a single binary module in any software version (Ex. foo.exe &#8211; Matlab-compiled exe) and check it: if the source code for this module has not changed since the last compilation then simply <b>don&#8217;t compile it</b>, just copy it from previous software version repository. Since most of our code doesn&#8217;t change daily (some of it hasn&#8217;t changed in years), we can skip the compilation time of most binaries and just copy them from some repository of previously compiled binaries.<br />
<span id="more-6919"></span><br />
In a broader look, avoiding lengthy compilations cycles by not compiling unchanged code is a common programming practice, implemented by all modern compilers. For example, the ‘make’ utility uses a ‘makefile’ to check the time stamps of all dependencies of every object file in order to decide which object requires recompilation. In reality, this is not always the best solution as time stamps may be incorrect, but it works well in the vast majority of cases.<br />
Coming back to Matlab, now comes the hard part – how could our build system know that nothing has changed in module X and that something has changed in module Y? How does it even know which source files it needs to ensure didn&#8217;t change?<br />
The credit for the idea goes to my manager, Lior Cohen, as follows: You can actually check the dependency of a given binary after compilation. <b>The basis of the solution is that a Matlab executable is in fact a compressed (zip) file</b>. The idea is then to:</p>
<ol>
<li>Compile the binary once</li>
<li>Unzip the binary and “see” all your dependencies (source files are encrypted and resources are not, but we only need the list of file names – not their content).</li>
<li>Now build a list of all your dependency files and compute the CRC value of each from the source control. Save it for the next time you are required to compile this module.</li>
<li>In the next compilation cycle, find this dependency list, review it, dependency source file at a time and make sure CRC of the dependency hasn’t changed since last time.</li>
<li>If no dependency CRC has changed, then copy the binary from the repository of previous software version, without compiling.</li>
<li>Otherwise, recompile the binary and rebuild the CRC list of all dependencies again, in preparation for the next compilation cycle.</li>
</ol>
<p>That&#8217;s it! That simple? Well&#8230; not really – the reality is a bit more complex since there are many other dependencies that need to be checked. Some of them are:</p>
<ol>
<li>Did the requested Matlab version of the binary change since the last compilation?</li>
<li>Did the compilation instructions themselves (we have a sort of ‘makefile’) change?</li>
</ol>
<p>Basically, I implemented a policy that if anything changed, or if the dependency check itself failed, then we don&#8217;t take any chances and just compile this binary. Keeping in mind that this dependencies check and file copying is much faster than a Matlab compilation, we save a lot of actual compilation time using this method.<br />
<b>Bottom line</b>: Given a software version containing hundreds of compilation instructions to execute and assuming not much has changed in the version (which is often the case), we skip over 90% of compilations altogether and only rebuild what really changed. The result is a version build that takes about half an hour, instead of many hours. Moreover, since the compilation process is working significantly less, we get fewer failures, fewer stuck or crashed mcc processes, and [not less importantly] less maintenance required by me.<br />
Note that in our implementation we rely on the undocumented fact that Matlab binaries are in fact compressed zip archives. If and when a future Matlab release will change the implementation such that the binaries will no longer be zip archives, another way will need to be devised in order to ensure the consistency of the target executable with its dependent source files.</p>
<h3 id="antivirus"><i>Don&#8217;t kill it, if it ain&#8217;t bad&#8230;</i></h3>
<p>I want to share a very weird issue I investigated over a year ago when using Matlab compiled exe. It started with a user showed me a Matlab compiled exe that didn&#8217;t run &#8211; I&#8217;m not talking about a regular Matlab exception: the process was crashing with an MS Windows popup window popping, stating something very obscure.<br />
It was a very weird behavior that I couldn&#8217;t explain – the compiler seemed to work well but the compiled executable process kept crashing. Compiling completely different code showed the same behavior.<br />
This issue has to do with the system compiler configuration that is being used. As you might know, when installing the Matlab compiler, before the first compilation is ever made, the user has to state the C compiler that the Matlab compiler should use in its compilation process. This is done by command ‘mbuild –setup’. This command asks the users to choose the C compiler and saves the configuration (batch file back then, xml in the newer versions of Matlab) in the user&#8217;s <i><b>prefdir</b></i> folder. At the time we were using Microsoft Visual C++ compiler 9.0 SP1.<br />
The breakthrough in the investigation came when I ran mcc command with <code>–verbose</code> flag, which outputs much more compilation info than I would typically ever want&#8230; I discovered that although the target executable file had been created, a post compilation step failed to execute, while issuing a very cryptic error message:</p>
<blockquote><p>mt.exe : general error c101008d: Failed to write the updated manifest to the resource of file &#8220;&#8230;&#8221;. Access is denied.</p></blockquote>
<p><center><figure style="width: 450px" class="wp-caption aligncenter"><a href="/images/deployment_error.png" target="_blank"><img decoding="async" alt="cryptic compilation error (click to zoom)" src="https://undocumentedmatlab.com/images/deployment_error.png" title="cryptic compilation error (click to zoom)" width="450" height="65" /></a><figcaption class="wp-caption-text">cryptic compilation error (click to zoom)</figcaption></figure></center><br />
The failure was in one of the ‘post link’ commands in the configuration batch file – something obscure such as this:</p>
<pre lang="bat">set POSTLINK_CMDS2=mt.exe -outputresource: %MBUILD_OUTPUT_FILE_NAME%;%MANIFEST_RESOURCE% -manifest "%MANIFEST_FILE_NAME%"</pre>
<p>This line of code takes an XML manifest file and inserts it into the generated binary file (<a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa375649(v=vs.85).aspx" rel="nofollow" target="_blank">additional details</a>).<br />
If you open a valid R2010a (and probably other old versions as well) Matlab-generated exe in a text editor you can actually see a small XML code embedded in it, while in a non-functioning exe I could not see this XML code.<br />
So why would this command fail?<br />
It turned out, as funny as it sounds, to be an antivirus issue – our IT department updated its antivirus policies and this ‘post link’ command suddenly became an illegal operation. Once our IT eased the policy, this command worked well again and the compiled executables stopped crashing, to our great joy.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-compilation-quirks-take-2">Matlab compilation quirks &#8211; take 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/quirks-with-compiled-matlab-dlls" rel="bookmark" title="Quirks with compiled Matlab DLLs">Quirks with compiled Matlab DLLs </a> <small>Several quirks with Matlab-compiled DLLs are discussed and workarounds suggested. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/quirks-with-parfor-vs-for" rel="bookmark" title="Quirks with parfor vs. for">Quirks with parfor vs. for </a> <small>Parallelizing loops with Matlab's parfor might generate unexpected results. Users beware! ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/secure-ssl-connection-between-matlab-and-postgresql" rel="bookmark" title="Secure SSL connection between Matlab and PostgreSQL">Secure SSL connection between Matlab and PostgreSQL </a> <small>It is tricky, but quite possible, to use SSL to connect Matlab to a PostgreSQL database. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-infiniband-with-matlab-parallel-computing-toolbox" rel="bookmark" title="Using Infiniband with Matlab Parallel Computing Toolbox">Using Infiniband with Matlab Parallel Computing Toolbox </a> <small>Infiniband networking can significantly improve PCT performance in Matlab parallelization and distributed computing. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-compilation-quirks-take-2/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>rmfield performance</title>
		<link>https://undocumentedmatlab.com/articles/rmfield-performance?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rmfield-performance</link>
					<comments>https://undocumentedmatlab.com/articles/rmfield-performance#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 25 May 2016 07:00:48 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Hanan Kavitz]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6427</guid>

					<description><![CDATA[<p>The performance of the builtin rmfield function (as with many other builtin functions) can be improved by simple profiling. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/rmfield-performance">rmfield 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/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/callback-functions-performance" rel="bookmark" title="Callback functions performance">Callback functions performance </a> <small>Using anonymous functions in Matlab callbacks can be very painful for performance. Today's article explains how this can be avoided. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/array-resizing-performance" rel="bookmark" title="Array resizing performance">Array resizing performance </a> <small>Several alternatives are explored for dynamic array growth performance in Matlab loops. ...</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><i>Once again I would like to introduce guest blogger <a href="http://www.mathworks.com/matlabcentral/profile/authors/2392999-hanan-kavitz" rel="nofollow" target="_blank">Hanan Kavitz</a> of <a href="http://appliedmaterials.com" rel="nofollow" target="_blank">Applied Materials</a>. Several months ago Hanan discussed some <a href="/articles/quirks-with-compiled-matlab-dlls" target="_blank">quirks with compiled Matlab DLLs</a>. Today Hanan will discuss how they overcame a performance bottleneck with Matlab&#8217;s builtin <b>rmfield</b> function, exemplifying the general idea that we can sometimes improve performance by profiling the core functionality that causes a performance hotspot and optimizing it, even when it is part of a builtin Matlab function. For additional ideas of improving Matlab peformance, search this blog for <a href="/tag/performance" target="_blank">&#8220;Performance&#8221; articles</a>, and/or get the book &#8220;<a href="/books/matlab-performance" target="_blank">Accelerating MATLAB Performance</a>&#8220;.</i><br />
<span class="alignright"><a href="/books/matlab-performance" target="_blank"><img fetchpriority="high" decoding="async" src="https://undocumentedmatlab.com/images/speedometer3b3c.gif" alt="Accelerating MATLAB Performance" title="Accelerating MATLAB Performance" width="276" height="275" /></a></span></p>
<p>I&#8217;ve been using Matlab for many years now and from time to time I need to profile low-throughput code. When I profile this code sometimes I realize that a computational &#8216;bottleneck&#8217; is due to a builtin Matlab function (part of the core language). I can often find ways to accelerate such builtin functions and get significant speedup in my code.</p>
<p>I recently found Matlab&#8217;s builtin <i><b>rmfield</b></i> function being too slow for my needs. It works great when one needs to remove a few fields from a small structure, but in our case we needed to remove thousands of fields from a structure containing about 5000 fields – and this is executed in a function that is called many times inside an external loop. The program was significantly sluggish.</p>
<p>It started when a co-worker asked me to look at a code that looked just slightly more intelligent than this:</p>
<pre lang="matlab">
for i = 1:5000
    myStruct = rmfield(myStruct,fieldNames{i});
end
</pre>
<p>Running this code within a tic/toc pair yielded the following results:</p>
<pre lang="matlab">
>> tic; myFunc(); t1 = toc
t1 =
      25.7713
</pre>
<p>In my opinion 25.77 secs for such a simple functionality seems like an eternity&#8230;<br />
<span id="more-6427"></span></p>
<p>The obvious thing was to change the code to the <a href="http://www.mathworks.com/help/matlab/ref/rmfield.html" rel="nofollow" target="_blank">documented</a> faster (vectorized) version:</p>
<pre lang="matlab">
>> tic; myStruct = rmfield(myStruct,fieldNames); t2 = toc
t2 =
      0.6097
</pre>
<p>This is obviously much better but since rmfield is called many times in my application, I needed something even better. So I profiled rmfield and was not happy with the result.</p>
<p>The original code of <i><b>rmfield</b></i> (<i>%matlabroot%/toolbox/matlab/datatypes/rmfield.m</i>) looks something like this (I deleted some non-essential code for brevity):</p>
<pre lang="matlab" highlight="9">
function t = rmfield(s,field)

  % get fieldnames of struct
  f = fieldnames(s);

  % Determine which fieldnames to delete.
  idxremove = [];
  for i=1:length(field)
    j = find(strcmp(field{i},f) == true);
    idxremove = [idxremove;j];
  end

  % set indices of fields to keep
  idxkeep = 1:length(f);
  idxkeep(idxremove) = [];

  % remove the specified fieldnames from the list of fieldnames.
  f(idxremove,:) = [];

  % convert struct to cell array
  c = struct2cell(s);

  % find size of cell array
  sizeofarray = size(c);
  newsizeofarray = sizeofarray;

  % adjust size for fields to be removed
  newsizeofarray(1) = sizeofarray(1) - length(idxremove);

  % rebuild struct
  t = cell2struct(reshape(c(idxkeep,:),newsizeofarray),f);
</pre>
<p>When I profiled the code, the highlighted row was the bottleneck I was looking for.</p>
<p>First, I noticed the string comparison equals to <code>true</code> part &#8211; while <code>'==true'</code> is not the cause of the bottleneck, it does leave an impression of bad coding style 🙁 Perhaps this code was created as some apprentice project, which might also explain its suboptimal performance.</p>
<p>The real performance problem here is that for each field that we wish to remove, <i><b>rmfield</b></i> compares it to all existing fields to find its location in a cell array of field names. This is algorithmically inefficient and makes the code hard to understand (just try &#8211; it took me hard, long minutes).</p>
<p>So, I created a variant of <i>rmfield.m</i> called <i>fast_rmfield.m</i>, as follows (again, omitting some non-essential code):</p>
<pre lang="matlab">
function t = fast_rmfield(s,field)
  % get fieldnames of struct
  f = fieldnames(s);
  [f,ia] = setdiff(f,field,'R2012a');

  % convert struct to cell array
  c = squeeze(struct2cell(s));

  % rebuild struct
  t = cell2struct(c(ia,:),f)';
</pre>
<p>This code is much shorter, easier to explain and maintain, but also (and most importantly) much faster:</p>
<pre lang="matlab">
>> tic; myStruct = fast_rmfield(myStruct,fieldNames); t3 = toc
t3 =
      0.0302
>> t2/t3
ans =
      20.1893
</pre>
<p>This resulted in a speedup of ~850x compared to the original version (of 25.77 secs), and ~20x compared to the vectorized version. A nice improvement in my humble opinion&#8230;</p>
<p>The point in all this is that we can and should rewrite Matlab builtin functions when they are too slow for our needs, whether it is found to be an algorithmic flaw (as in this case), extraneous sanity checks (as in the case of <a href="/articles/ismembc-undocumented-helper-function" target="_blank"><i><b>ismember</b></i></a> or <a href="/articles/datenum-performance" target="_blank"><i><b>datenum</b></i></a>), bad default parameters (as in the case of <a href="/articles/improving-fwrite-performance" target="_blank"><i><b>fopen/fwrite</b></i></a> or <a href="/articles/undocumented-scatter-plot-behavior" target="_blank"><i><b>scatter</b></i></a>), or merely slow implementation (as in the case of <a href="/articles/improving-save-performance" target="_blank"><i><b>save</b></i></a>, <a href="/articles/cellfun-undocumented-performance-boost" target="_blank"><i><b>cellfun</b></i></a>, or the <a href="/articles/convolution-performance" target="_blank"><i><b>conv</b></i> family of functions</a>).</p>
<p>A good pattern is to save such code pieces in file names that hint to the original code. In our case, I used <i><b>fast_rmfield</b></i> to suggest that it is a faster alternative to <i><b>rmfield</b></i>.</p>
<p><i>Do you know of any other example of a slow implementation in a built-in Matlab function that can be optimized? If so, please leave a comment below.</i></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/rmfield-performance">rmfield 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/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/callback-functions-performance" rel="bookmark" title="Callback functions performance">Callback functions performance </a> <small>Using anonymous functions in Matlab callbacks can be very painful for performance. Today's article explains how this can be avoided. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/array-resizing-performance" rel="bookmark" title="Array resizing performance">Array resizing performance </a> <small>Several alternatives are explored for dynamic array growth performance in Matlab loops. ...</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/rmfield-performance/feed</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
		<item>
		<title>Quirks with compiled Matlab DLLs</title>
		<link>https://undocumentedmatlab.com/articles/quirks-with-compiled-matlab-dlls?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=quirks-with-compiled-matlab-dlls</link>
					<comments>https://undocumentedmatlab.com/articles/quirks-with-compiled-matlab-dlls#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 10 Feb 2016 19:00:00 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Compiler]]></category>
		<category><![CDATA[Hanan Kavitz]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6262</guid>

					<description><![CDATA[<p>Several quirks with Matlab-compiled DLLs are discussed and workarounds suggested. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/quirks-with-compiled-matlab-dlls">Quirks with compiled Matlab DLLs</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/matlab-compilation-quirks-take-2" rel="bookmark" title="Matlab compilation quirks &#8211; take 2">Matlab compilation quirks &#8211; take 2 </a> <small>A few hard-to-trace quirks with Matlab compiler outputs are explained. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-compiled-apps-startup" rel="bookmark" title="Speeding up compiled apps startup">Speeding up compiled apps startup </a> <small>The MCR_CACHE_ROOT environment variable can reportedly help to speed-up deployed Matlab executables....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/quirks-with-parfor-vs-for" rel="bookmark" title="Quirks with parfor vs. for">Quirks with parfor vs. for </a> <small>Parallelizing loops with Matlab's parfor might generate unexpected results. Users beware! ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/docking-figures-in-compiled-applications" rel="bookmark" title="Docking figures in compiled applications">Docking figures in compiled applications </a> <small>Figures in compiled applications cannot officially be docked since R2008a, but this can be done using a simple undocumented trick....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I would like to introduce guest blogger <a href="http://www.mathworks.com/matlabcentral/profile/authors/2392999-hanan-kavitz" rel="nofollow" target="_blank">Hanan Kavitz</a> of <a href="http://www.appliedmaterials.com" rel="nofollow" target="_blank">Applied Materials</a>. Today Hanan will discuss several quirks that they have encountered with compiled Matlab DLLs.</i><br />
I work for Applied Materials Israel (PDC) in the algorithm development department. My group provides Matlab software solutions across all of our products. I am a big fan of Yair&#8217;s blog and was happy to receive an invitation to be a guest blogger.<br />
In PDC we are using Matlab compiler and Java Builder to deploy our algorithmic products at the customer sites. The software we produce includes binaries of three sorts: exe, C++ dlls, and jar files, all compiled using Matlab deployment tools.<br />
C++ dlls are not as common and are a relatively new kind of binary in production so there’s not as much experience using them in PDC and from time to time we discover weird behaviors that might be interesting to the readers. Here are three of the latest quirks that we encountered:<br />
<span id="more-6262"></span></p>
<h3 id="tmp">Leftover tmp files</h3>
<p>Recently I faced a problem that googling revealed that I might be the first to encounter it (outside MathWorks development team) as there was no mention of this anywhere. It all started when I got a mail from a fellow developer with content of the type: “<i>Hi Hanan, what are these dump files for ???</i>” and a screenshot of <i><b>tempdir</b></i> showing multiple tmp files that all had a naming convention of ‘mathworks_tmp_XXX_YYY’ (xxx and yyy being some numbers, presumably process ids):<br />
<center><figure style="width: 414px" class="wp-caption aligncenter"><a href="/images/compiler_tmp_files.jpg" target="_blank"><img decoding="async" alt="multiple leftover tmp files in tmpdir (click for details)" src="https://undocumentedmatlab.com/images/compiler_tmp_files.jpg" title="multiple leftover tmp files in tmpdir (click for details)" width="414" height="227" /></a><figcaption class="wp-caption-text">multiple leftover tmp files in tmpdir (click for details)</figcaption></figure></center><br />
Each file was about 43MB in size, and combined they consumed the entire free space in the hard-disk, preventing applications from lunching.<br />
At first I looked in our code for the code that will produce files with this naming convention and once I was sure there is no such code I was comfortable to assume that they are MathWorks internal-use files (indeed – who other than MathWorkers would call their files <i>mathworks_tmp_&#8230;</i>).<br />
Compiling and running a small ‘hello world’ C++ dll showed that every time that a Matlab-compiled C++ dll executed and ran, a temp file is created and then deleted in the <i>%tmp%</i> dir (<i><b>tempdir</b></i>). If the process that runs this dll is ‘killed’ during the run, the temp file is not deleted and remains in the <i>%tmp%</i> folder, accumulating over time until the hard disk becomes completely full.<br />
On another machine I found a whole bunch of different temp files with different extensions. Opening them in editor didn&#8217;t reveal their purpose. They all had two things in common:</p>
<ol>
<li>All had a naming convention <i>mathworks_tmp_XXX__YYY</i>, whatever the extension of the file may be.</li>
<li>They are all useless when the Matlab application is done running.</li>
</ol>
<p>Once this was clear, the solution was very simple:</p>
<ul>
<li>When lunching the process that runs Matlab compiled dll, change the <i>%tmp%</i> directory to a new one.</li>
<li>Delete this directory once done running or on the next process start.</li>
</ul>
<h3 id="mclInitializeApplication">mclInitializeApplication</h3>
<p>As a separate discussion, our compiled algorithm is <a href="https://en.wikipedia.org/wiki/Embarrassingly_parallel" rel="nofollow" target="_blank">embarrassingly parallel</a> in nature so our C++ team is running it in parallel processes across several machines and many cores.<br />
As with all Matlab-compiled C++ DLLs, it needs to be initialized with a call to <i><b>mclInitializeApplication</b></i> per running process. This worked well when we had a relatively small number of processes running concurrently but lately we encountered a problem that out of dozens of calls to this function from time to time a call is stuck (not failed – exactly that: stuck) and the process needs to be killed.<br />
We don’t know why this happens and the solution we are currently using is pretty “shaky” at best – we retry the call to this function several times until it eventually works (and it does work after several tries).<br />
I have a suspicion that something is not entirely parallel with this function and there exists some hidden internal shared resource among different processes but no way to know exactly as this is an internal MathWorks function.</p>
<h3 id="multithreading">Implicit multithreading</h3>
<p>This is relatively old issue we encountered at the beginning when we just started using Matlab-compiled DLLs, so this might not surprise some readers. While Matlab&#8217;s builtin (automatic) multithreading is great when used in the MATLAB IDE (non-compiled), it creates a problem when running compiled DLLs in parallel across multiple processes: this multithreading ‘starves’ for cores because they are busy at running other processes.<br />
The solution is simple and well documented – when calling <i><b>mclInitializeApplication</b></i> before launching the DLL, pass it the <i>singleCompThread</i> flag to prevent implicit multithreading. We found this single threaded DLL to run faster because it reduced CPU ‘starvation’ drastically in a multi process environment.</p>
<h3 id="addendum">Addendum (by Yair again):</h3>
<p><i>I am delighted to announce that a few days ago I received an apparently-automated email from MathWorks telling me that 4 of the issues that I have reported early last year were fixed in R2015b. IMHO, this marks a very important step of closing the loop with the original issue reporter, something that I have <a href="/articles/couple-of-matlab-bugs-and-workarounds#comment-339302" rel="nofollow" target="_blank">suggested publicly</a> back in December 2014 (and also privately over the years). I believe that such automated feedbacks increase user motivation to report misbehaving or missing features, which will ultimately make Matlab better for the benefit of us all. I also believe that this proves once again my claim that beneath the corporate jargon, MathWorks is indeed a company run by engineers like us, who cares about its users and the interaction with them more than typical in the corporate world. I can only praise this email and hope that it is now part of the ongoing development release process, rather than being an isolated case. If I may suggest a followup improvement, it would be nice to receive such emails before the new release is out (i.e., during the beta phase) so that the original reporter could have a chance to test it on the beta before it actually goes live. But in any case, thanks MathWorks for listening and making yet another improvement 🙂<br />
Happy New Year of the Monkey everybody!</i></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/quirks-with-compiled-matlab-dlls">Quirks with compiled Matlab DLLs</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/matlab-compilation-quirks-take-2" rel="bookmark" title="Matlab compilation quirks &#8211; take 2">Matlab compilation quirks &#8211; take 2 </a> <small>A few hard-to-trace quirks with Matlab compiler outputs are explained. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-compiled-apps-startup" rel="bookmark" title="Speeding up compiled apps startup">Speeding up compiled apps startup </a> <small>The MCR_CACHE_ROOT environment variable can reportedly help to speed-up deployed Matlab executables....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/quirks-with-parfor-vs-for" rel="bookmark" title="Quirks with parfor vs. for">Quirks with parfor vs. for </a> <small>Parallelizing loops with Matlab's parfor might generate unexpected results. Users beware! ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/docking-figures-in-compiled-applications" rel="bookmark" title="Docking figures in compiled applications">Docking figures in compiled applications </a> <small>Figures in compiled applications cannot officially be docked since R2008a, but this can be done using a simple undocumented trick....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/quirks-with-compiled-matlab-dlls/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
