What is the most efficient way: load or set global variable

16 ビュー (過去 30 日間)
NMTri
NMTri 2013 年 12 月 31 日
コメント済み: NMTri 2014 年 1 月 8 日
I'm working with a script that calls a function several times (about 1000); in this function, a large complex-valued matrix is used, this matrix called "promat" is saved in file also named "promat.mat". To be specific, my function is following:
function y=process(x)
do something with x
y=x.*promat;
end
I think about three solutions:
+ First: load promat to work space, then set it as global variable and declare it in the function.
+ Second: load promat to work space, then set it as an input of the function as:
function y=process(x,promat)
+ Third: load the matrix inside the function.
I wonder what is the fastest and most efficient way to do it, both in memory use efficiency and performance. Any answers and discusses will be appreciated :).

採用された回答

Amit
Amit 2013 年 12 月 31 日
編集済み: Amit 2013 年 12 月 31 日
If you don't change the values for promat inside the function, Matlab will not be allocating a new memory for promat. As long a promat serves only the purpose of being read inside your function, option second is better.
I would avoid the declaring global variable. Also loading the promat.mat inside the matrix will create extra overheads and most likely reduce performance.
  3 件のコメント
Walter Roberson
Walter Roberson 2013 年 12 月 31 日
"global" is relatively slow. A shared variable (used by a nested function) should be faster.
NMTri
NMTri 2014 年 1 月 8 日
Thanks for your link and explanation. My code works well and faster with the second option.

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

その他の回答 (1 件)

Jan
Jan 2013 年 12 月 31 日
Reuse the memory of x:
function x = process(x)
do something with x
x = x .* promat;
end
Then consider, that writing this question took about 2 minutes. Will the sum of the saved computing time ever exceed these 2 minutes? If not, this is a typical example of "premature optimization".
Code should be optimized, when it is written completely and tested successfully. Then profiling must identify the bottleneck, because it is a waste of time to improve a part of the program, which takes a small part of the total computing time only.
Anyway, I agree with Sean and Walter: Avoid disk access and reduce the use of globals whenever possible.
  1 件のコメント
NMTri
NMTri 2014 年 1 月 8 日
Thanks for the suggests about "premature optimization" and code optimization, I also considered them when writing my code and this question.
By the way, the input matrix is real, and output matrix is complex, since "promat" is complex, so is it efficient when reusing memory? I read about memory optimization in matlab and they said that we should not assign complex value to already assigned real valued matrix.

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by