Why does declaring a global variable take so much time?
6 次查看(过去 30 天)
显示 更早的评论
I have a function in from a larger program that I profiled in order to try and find some places to gain some speed. The global declaration in the function below takes up by far the most time. Can anyone tell me why this would take so much time and suggest possible solutions? Unfortunately, giving it as an argument to the function is not an option.
1 个评论
Stephen23
2020-8-13
"As far as I was aware ode45 needs an ode function that has just two arguments."
"However, looking a bit deeper, there is a way to pass more arguments."
采纳的回答
José-Luis
2014-2-10
编辑:José-Luis
2014-2-10
Just a quick test:
num = 100000000;
tic
a = 1;
for ii = 1:num;
a = ii;
end
toc
global b;
b = 1;
for ii = 1:num;
b = ii;
end
toc
The problem with allocating globals is that ALL programs that are running must be made aware: "Look here, I'm a global and I demand your attention", so that's an overhead. All the normal tricks that a program could do to optimize the use of normal arrays go out the window when you make them globals. Also, and maybe this is not applicable here, good luck making your program thread safe. The solution:
- Don't use globals, but you don't want to hear that
- Pass them explicitly, something else you don't want to hear.
- Don't modify them so often.
3 个评论
José-Luis
2014-2-10
编辑:José-Luis
2014-2-10
You might only need it to be accessible to two functions, but there is no way for Matlab to know that.
"The setter function doesn't view it as a global variable". Are you sure? You only need declare global once. All subsequent call will treat a variable with that name as global. There is no way to make a global local again, if you understand what I mean.
Well, if you can't change the parent function (why?) then I can't think of any other way of passing the values of P to the child. Not one that is straightforward and safe that is.
更多回答(1 个)
Walter Roberson
2014-2-10
Try mechanisms such as
setter: setappdata(0,'P', P);
your function: P = getappdata(0, 'P');
4 个评论
José-Luis
2014-2-10
That might well be, but it would have the disadvantages of a global, save that you need to explicitly call it. Might make debugging a pain. Oh well...
Walter Roberson
2014-2-10
One of the problems with global variables is that people accidentally reuse the name for local purposes, thus overwriting the global version. If the only way to overwrite the global version is to code a setappdata() call, then that is not going to happen accidentally.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Scope Variables and Generate Names 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!