Speed performance between class, struct and local variable
11 次查看(过去 30 天)
显示 更早的评论
Here is the illustration of my problem :
% Class
classdef MaClasse < handle
properties (Access = public)
vec1 = [];
vec2 = [];
vec3 = [];
end
end
...
nb = 50000;
randstream = Randstream('mrg32k3a');
% Cas 1
pObj = MaClasse();
pObj.vec1 = randn(randstream,100,1000);
pObj.vec2 = randn(randstream,100,1000);
pObj.vec3 = randn(randstream,100,1000);
tic
for i=1:nb
pObj.vec1 = pObj.vec1.*pObj.vec2 + pObj.vec3;
end
toc
% ----> 6.80 seconds
% Cas 2
vec1 = randn(randstream,100,1000);
vec2 = randn(randstream,100,1000);
vec3 = randn(randstream,100,1000);
tic
for i=1:nb
vec1 = vec1.*vec2 + vec3;
end
toc
% ----> 1.61 seconds
% Cas 3
str.vec1 = randn(randstream,100,1000);
str.vec2 = randn(randstream,100,1000);
str.vec3 = randn(randstream,100,1000);
tic
for i=1:nb
str.vec1 = str.vec1.*str.vec2 + str.vec3;
end
toc
% ----> 6.95 seconds
A difference of factor 4 seems critical to use Matlab with POO (even with struct according to my test)
If someone has a solution but not to say using local variable and then copy into attributs ;-)
0 个评论
采纳的回答
Matt J
2024-2-7
编辑:Matt J
2024-2-7
Well Case 1 and Case 3 have more indexing operations, so it makes sense that that overhead should dominate assuming the + and .* operations are sufficiently fast. That seems to be the case, because below we see that once the data size is sufficiently large, the relative differences in performance diminish. It just shows how fast .* and + are for small/medium data sizes!
rs = RandStream('mrg32k3a');
M=5000; N=5000;
% Cas 1
pObj = MaClasse();
pObj.vec1 = randn(rs,M,N);
pObj.vec2 = randn(rs,M,N);
pObj.vec3 = randn(rs,M,N);
str.vec1 = randn(rs,M,N);
str.vec2 = randn(rs,M,N);
str.vec3 = randn(rs,M,N);
vec1 = randn(rs,M,N);
vec2 = randn(rs,M,N);
vec3 = randn(rs,M,N);
timeit( @() pObj.vec1.*pObj.vec2 + pObj.vec3 )
timeit( @() str.vec1.*str.vec2 + str.vec3 )
timeit( @() vec1.*vec2 + vec3 )
2 个评论
Matt J
2024-2-8
It means that if you're using class in a complex simulation calculation code with Matlab, you have to accept that it will be less efficient
I don't think it means it's less efficient just because it takes longer. It takes longer because you are giving it more work.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Performance and Memory 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!