Optimizing the print function in Matlab

2019-07-18 10:18发布

问题:

I maintain a software package that automates ingestion of data. When raw data is imported, it is plotted and some graphics of the data are saved to disk. Unfortunately, the print function dramatically slows my performance.

Here is a breakdown of the code performance

Script       Time
myscript     9.091s
uichoosefile 3.567s
print        4.178s
legend       0.751s

Only about 3/4s of my execution time is real processing time and print is the biggest timesink here.

Inside print two lines take up almost 100% of the time

Line Code                                Time
212  pj = pj = alternatePrintPath(pj);   3.173s
148  drawnow;                            0.751s

How can I create an optimized version of print that isn't bottlenecked by these two lines? Simple optimization routines such as lowering graphics resolution are not desirable.

回答1:

Matlab is actually rather special in that it is pretty easy to optimize its internal functions. I did this to ode15s in a systems biology modelling toolbox that I wrote.

This is how you do it yourself:

  1. Make a new folder. I'll call it image_print.
  2. Add that folder to the Matlab path so you can use it anywhere addpath('image_print')
  3. Copy the function you want to optimize into the new folder image_print and give the file a new name. I'll call it printimage.m.
  4. In the folder where the original function was, there will be a folder called private. Copy that folder into your new folder image_print. Keep the name as private.

Now you can use printimage and optimize it without screwing up the rest of Matlab. What actually helps will depend entirely on your actual workflow and require a fair amount of cleverness on your part. You are starting from the right spot by using the profiler. Basically, you'll have to figure out via trial and error what the slow steps are doing and then see if there is a faster way to do it specifically for your work. The original function is very general, so you will be able to cut entire sections out. Don't forget that you can modify the functions in private also.

Bonus suggestion: Because you only want save the figures to disk, you might want to focus on preventing them from wasting time actually drawing to the screen. You might be able to comment out the drawnow line entirely, but please report back on what actually happens.