Matlab function slow first time, much faster subsequently. Why?

6 views (last 30 days)
I have a large MATLAB function file. It first creates a zero matrix, then updates about 70% of the cells by evaluating a number of corresponding (long) algebraic expressions that are hard coded in the function. Once this is complete, a numeric matrix is returned.
The .m file is about 4MB large (I have 100 of these m. files, but that is not directly relevant). When I evaluate the function the first time, it takes about 9s to evaluate. Subsequent runs, however, only take about 0.1s, which is more what I was expecting.
Why does the first evaluation take 9s? Anytime I close and reopen matlab, I each time have this slow first evaluation, with subsequent runs being much faster. Why is this?
The m. file can be found at the below public link (you can copy the text from the browser): https://dl.dropboxusercontent.com/u/157153767/K_a_12_102x.m
The command window input you should use is: [test]=K_a_12_102x(414000000,1.1095e+09,1.2500e-04,0.0840,0.0840,0.0240,0.0240,0.0020,0.0020,0,0,0,0,3.0397e+08,8.9930e+07,0,3.0397e+08,0,1.0702e+08,0,0,0,0,0,0,497.7389,80.7355,-15.9811,391.1985,-15.9811,103.5248,20440000,0,20440000,0.06)

Accepted Answer

dpb
dpb on 21 Oct 2013
Matlab is interpreted so when the extremely large code file is read the first time the JIT compiler has to first load it into memory, parse it and compile it. Once that is done, the function is cached in memory until it is released by memory (say by a clear). Obviously when the Matlab session is closed anything in memory is lost so the whole process has to be redone next time.
It's an inevitable result of having such a large function...whether you might gain by factoring into more smaller functions I don't know--I've certainly never tried writing such large m-files.
  2 Comments
Kobye
Kobye on 21 Oct 2013
Thanks very much for your reply which has some good advice. Apparently I may be able to overcome this problem by transferring the number crunching part of the code to C, C# or something similar and including it as dll. This negates the need for JIT compiling everytime I start MATLAB.
As an aside, these 4MB files are already the "smaller" functions, hence why I have 100 of them!

Sign in to comment.

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!