Speed performance between class, struct and local variable
11 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Franck AUBINEAU
el 7 de Feb. de 2024
Comentada: Matt J
el 8 de Feb. de 2024
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 comentarios
Respuesta aceptada
Matt J
el 7 de Feb. de 2024
Editada: Matt J
el 7 de Feb. de 2024
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 comentarios
Matt J
el 8 de Feb. de 2024
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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Performance and Memory en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!