Performance penalty of persistent variables in MATLAB -


recently profiled matlab code , shocked see following in heavily used function:

5.76  198694   58 persistent constants;  3.44  198694   59 if isempty(constants) % initialize constants 

in other words, matlab spent 9 seconds, on 198694 function calls, declaring persistent constants , checking if has been initialized. represents 13% of total time spent in function.

do persistent variables carry of performance penalty in matlab? or doing terribly wrong here?

update

@andrew tried sample script , very, perplexed output:

time   calls  line                 6 function has_persistent 6.48  200000    7 persistent constants  1.91  200000    8 if isempty(constants)                  9     constants = 42;                10 end 

i tried bench() command , showed machine in middle range of sample machines. running ubuntu 64 bits on intel(r) core(tm) i7 cpu, 4gb ram.

that's standard way of using persistent variables in matlab. you're doing you're supposed to. there noticable overhead it, timings seem kind of surprisingly high.

here's similar test ran in 32-bit matlab r2009b on 3.0 ghz intel core 2 qx9650 machine under windows xp x64. similar results on other machines , versions. 5x faster timings.

test:

function call_has_persistent = 1:200000     has_persistent(); end  function has_persistent persistent constants if isempty(constants)     constants = 42; end 

results:

  0.89  200000    7 persistent constants    0.25  200000    8 if isempty(constants)  

what matlab version, os, , cpu running on? constants initialized with? matlab's bench() output seem reasonable machine?

your timings seem high. there may bug or config issue there fix. if want matlab code fast, standard advice "vectorize" it: restructure code makes fewer function calls on larger input arrays, , makes use of matlab's built in vectorized functions instead of loops or control structures, avoid having 200,000 calls function in first place. if possible. matlab has relatively high overhead per function or method call (see is matlab oop slow or doing wrong? numbers), can more mileage refactoring eliminate function calls instead of making individual function calls faster.

it may worth benchmarking other basic matlab operations on machine, see if it's "persistent" seems slow. try profiling little call_has_persistent test script in isolation see if context of function makes difference.


Comments

Popular posts from this blog

unicode - Are email addresses allowed to contain non-alphanumeric characters? -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

c++ - Convert big endian to little endian when reading from a binary file -