Working with global variables is fast?
조회 수: 2 (최근 30일)
이전 댓글 표시
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
Geoff
2012년 3월 30일
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.
답변 (2개)
per isakson
2012년 3월 29일
댓글 수: 1
James Tursa
2018년 1월 25일
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
2012년 3월 29일
댓글 수: 3
Geoff
2012년 3월 30일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Import and Analysis에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!