Why is the code so slow?
Mostrar comentarios más antiguos
Hello,
could please someone explain to me, why the second part of this code is so slow?
clear
% A = zeros(360,100000);
tic
for m = 1 : 1000
b =rand(360,1);
B(:,m) = b;
end
toc
iter = 1000;
L = 360;
A = ClassTestZeit('foo', 5, 4, L, iter);
tic
for m = 1: iter
A = A.func1(L,m);
end
toc
Here is the class:
classdef ClassTestZeit
properties (SetAccess = public, GetAccess = public)
name string
mu(1,1) double
ku(1,1) double
matrix(:,:) double
end
methods
function obj = ClassTestZeit(name, mu, ku, t, iter)
obj.name = name;
obj.mu = mu;
obj.ku = ku;
obj.matrix = zeros(t,iter);
end
function obj = func1(obj,L, iter)
obj.matrix(:,iter) = obj.func2(L);
end
function out = func2(~, L)
out = rand(L,1);
end
end
end
The property "matrix" is preallocated, but it still talks much longer, then the first part.
What I am doing wrong? is there a way to speed it up, and still use OOP.
I hope, that somebody cann help my.
3 comentarios
Image Analyst
el 10 de Feb. de 2023
Why are you overwriting the class variable instance "A" with a Lx1 vector of random numbers? The functions of A won't work after that.
Julian
el 10 de Feb. de 2023
Walter Roberson
el 10 de Feb. de 2023
It is a value class and each time a revised object is being returned and overwrites the previous object. This is semantically valid, even if inefficient.
Respuestas (1)
Walter Roberson
el 10 de Feb. de 2023
0 votos
- every interaction with an object other than copying the object as a whole, requires making function calls. MATLAB does not internally compile the references down to minimal form like a C++ compiler could potentially do. At any point during execution you might potentially inject a breakpoint into a class method and the breakpoint must be taken: the methods must be executed as-written, not distilled down to their essence like a compiler potentially could.
- you are using a value class, so your object is "copy on write". During any one call into an object method, the first time you modify any property of the object, MATLAB has to clone the object infrastructure (but it can increment reference counts of stored property values and store pointers to them, instead of having to deep copy all of the values associated with the object.) This is going to be slower than a plain loop.
If you ever need to hold on to the "old" version of the object along with the new version, you might indeed need a value class. But if every time that you call a method that modifies an object property, your invoking code overwrites the object with the result, then consider using a handle class instead of a value class.
1 comentario
Julian
el 11 de Feb. de 2023
Categorías
Más información sobre Performance and Memory en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!