Why does it take so long to run a function?

9 ビュー (過去 30 日間)
Jeff Ack
Jeff Ack 2019 年 1 月 30 日
コメント済み: Jeff Ack 2019 年 1 月 30 日
I'm using a user-created function in my code that I have to evaluate a lot of times. The function is running relatively slow. I looked closer and saw that the function actually evaluates quickly; it's the process of calling the function that takes a long time. An example will likely make this easier:
function [ test_output ] = fn_test( X)
tic
inv(rand(1000,1000))*X;
toc
endfunction
tic
fn_test(3);
toc
My computer gave an elapsed time of 0.09 seconds for the first "toc" (inverting the random matrix and multiplying) but a time of 0.302 seconds for the second "toc" (actually running the function).
Any idea why this is the case, and what (if anything) I can do about it?
  1 件のコメント
Stephen23
Stephen23 2019 年 1 月 30 日
編集済み: Stephen23 2019 年 1 月 30 日
endfunction
This is clearly not MATLAB code, so how are we supposed to be able to help you? Given that code runtime depends on the interpreter, why do you think that advice about MATLAB would help your non-MATLAB code? You are asking about timing of features (e.g. calling of functions) that depend on the interpreter that you are using (which is not MATLAB).
Also note that inv is rarely needed, and is not a good way to solve systems of equations.

サインインしてコメントする。

採用された回答

Jan
Jan 2019 年 1 月 30 日
If I change "endfunction" to end to convert your Octave code to Matlab, Matlab show an equivalent behaviour:
Elapsed time is 0.041 seconds
Elapsed time is 0.058 seconds
Of course calling a function has a certain overhead. That this is 0.21 seconds in your case, is strange. This might mean, that the memory manager of Ocatve has a problem to clean up the used memory. Nevertheless, this is not a problem concerning Matlab.
  1 件のコメント
Jeff Ack
Jeff Ack 2019 年 1 月 30 日
Thank you. I completely forgot that the function syntax is different, and I definitely would not have asked the question if I'd realized it was Octave-specific (I'm a MATLAB veteran, but I recently switched to Octave because I no longer have my university affiliation. Hopefully I'll have MATLAB back soon)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by