MATLAB takes a long time after last line of a function

I have a function that's taking a long time to run. When I profile it, I find that over half the time (26 out of 50 seconds) is not accounted for in the line by line timing breakdown, and I can show that the time is spent after the function finishes running but before it returns control by the following method:

ts1 = tic;
disp ('calling function');
functionCall(args);
disp (['control returned to caller - ', num2str(toc(ts1))]); 

The first line of the function I call is ts2 = tic, and the last line is

disp (['last line of function- ', num2str(toc(ts2))]);

The result is

calling function

last line of function - 24.0043

control returned to caller - 49.857

Poking around on the interwebs, I think this is a symptom of the way MATLAB manages memory. It deallocates on function returns, and sometimes this takes a long time. The function does allocate some large (~1 million element) arrays. It also works with handles, but does not create any new handle objects or store handles explicitly. My questions are:

  1. Is this definitely a memory management problem?
  2. Is there any systematic way to diagnose what causes a problem in this function, as opposed to others which return quickly?
  3. Are there general tips for reducing the amount of time MATLAB spends cleaning up on a function exit?
8
задан Mikhail 24 November 2010 в 18:22
поделиться