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

조회 수: 14 (최근 30일)
Kobye
Kobye 2013년 10월 21일
댓글: dpb 2013년 10월 21일
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)

채택된 답변

dpb
dpb 2013년 10월 21일
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
Kobye
Kobye 2013년 10월 21일
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!
dpb
dpb 2013년 10월 21일
Or you can turn them into mex functions...

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by