Working with global variables is fast?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Here is my problem I am goint write a large program and at the begining I want to decide the way that I will code in order to run my program fast.
In my program there will be a huge martix and transfering it from functions to functions may be time consuming. Hence is it posible to work with functions on main variable with out copying it on memory. I try to declerate global variable but nothing changes since functions are copying it on the memory too.
In fact, what I would like to get is instead of trasnfering huge data to functions and getting my data back, let the data to be stationary while functions work on it.
Here is an example to compare the running time. Please be awere of that this is just an example to get running time.
Resaults are:
Elapsed time is 0.000088 seconds. (running it on main function)
Elapsed time is 0.000767 seconds. (transfering data to functions)
Elapsed time is 0.000753 seconds. (using a global variable)
Any suggestions? ----------------------------------------------
function main
clear;
clear global;
clc;
a=1:10000;
tic
for i=1:10000
a(i)=a(i)+1;
end
toc
a=1:10000;
tic
a=nonglobalfunction(a);
toc
global A
A=1:10000;
tic
globalfunction()
toc
end
function globalfunction
global A
for i=1:10000
A(i)=A(i)+1;
end
end
function a=nonglobalfunction(a)
for i=1:10000
a(i)=a(i)+1;
end
end
1 commentaire
Geoff
le 30 Mar 2012
By the way, you are testing such tiny execution times that it's hard to get a meaningful result. The usual approach here is to repeat each test maybe 5000 times and measure the entire loop. Divide the resulting time by 5000 and you'll have a metric that is useful for comparison.
Réponses (2)
per isakson
le 29 Mar 2012
1 commentaire
James Tursa
le 25 Jan 2018
Another related option that was just posted to the FEX for getting shared data copies of contiguous sub-sections of an existing variable:
Volkan Kandemir
le 29 Mar 2012
3 commentaires
Geoff
le 30 Mar 2012
Have you considered putting your information into a class and just pass around a handle to your object? I haven't used classes in MatLab, but (correct me if I'm wrong) I understand that the object's handle is effectively a pointer, and passing around an object this way will not result in it being copied.
Voir également
Catégories
En savoir plus sur Data Import and Analysis dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!