Reputation: 2564
I noticed that if I have Matlab code where my figure has to display a legend, the running time increases significantly.
Here's an example:
clear all
close all
clc
% legend test
x = [0:1:100];
y = x.^(3.123);
figure('Name', 'X-Y and X-X plot')
plot(x,y)
hold all
plot(x,x)
legend('1', '232')
Gives a running time of 1.1 seconds. Same code without the legend('1', '232')
line has an execution time of 0.4 seconds. I find it very odd that a simple legend increases the running time this much.
With the profiler I found that the function mainly responsible for the time increase is called graphics/private/texmex
. It has a self-time of 0.12 seconds and is called 4 times. When I don't create a legend this function is not called.
Is there a way to speed up my code, while still generating a legend in a figure?
I'm running 64-bit Matlab 2012b on Mac OS 10.8.3.
When I run the code in the example with set(0, DefaultTextInterpreter, 'none')
the texmex
function is called by tex>localCallTeXParser
, which is called by scribe.legend.methods>strsize
, etc...:
graphics/private/texmex
tex>localCallTeXParser
scribe.legend.methods>strsize
scribe.legend.methods>getsizeinfo
scribe.legend.methods>getsize
scribe.legend.methods
scribe.legend.legend
Upvotes: 0
Views: 1865
Reputation: 46
I had the same issue with a project of my own. I wanted to dynamically update some line plots quickly using a slider, but noticed that the having a legend active really killed the performance I was getting.
I found the solution to my problem here - http://undocumentedmatlab.com/blog/plot-performance/.
From the second listed performance hack, I added the lines
set(gca,'LegendColorbarListeners',[]);
setappdata(gca,'LegendColorbarManualSpace',1);
setappdata(gca,'LegendColorbarReclaimSpace',1);
to my code. I got an error message for the first line of code that was mentioned, so I struck it out above. Regardless though, the other two lines of code made my plots update just as quickly with a legend as they did without the legend being present.
Upvotes: 3
Reputation: 4551
Sounds like legend
is using a TeX interpreter (at least, that's what texmex
sounds like). In that case, you could try
legend({'1', '232'}, 'Interpreter', 'none');
This will disable the TeX interpreter and therefore may improve the performance. I should probably note that I've never experienced any trouble with the speed of the legend
function, so it's probably something specific to your plots and/or MATLAB installation/version.
Edit: I have the feeling that the above will draw the legend with the TeX interpreter first, then disable it and draw it again. Try doing the following before drawing the legend or perhaps before drawing the figure (not sure at which point MATLAB will promote the default properties to an actual figure / axes / legend):
set(0, 'DefaultTextInterpreter', 'none');
Upvotes: 1