Inconsistent assignment time for matrix inside a class
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi,
My previous question maybe not clear enough. Hopefully this is clearer.
Suppose I have a handle class o with a property o.x, which is a n by n double matrix.
Does matlab gurantee that "o.x(1,1) = 1;" take O(1) time? Or it can take O(n^2) time?
Somehow in my program, sometimes that sentences take O(n^2) time.
Our of many runs of my program, it happens only sometimes and I am not able to produce the example consistently.
See below for more details.
=== Old Version ====
I have a handle class looks like the following:
classdef SlowClass < handle
properties
x = zeros(1000,0);
end
methods
function append(o)
o.x(:,end+1) = 1;
end
end
end
Sometimes, after enough o.append(), the program becomes very slow. (even when I still have >40GB unused ram.)
When it is slow, I pause the program and run the following in debug mode
tic;
for i = 1:1000
o.x(1,1)=1;
end
toc;
Elapsed time is 9.414806 seconds. (When the program is fast, in debug mode, this takes microseconds instead.)
However, if I restart the matlab, it becomes normal again (until a long while).
I tried profiling the for loop "tic;for i = 1:1000, o.x(1,1)=1;end; toc;" when it is slow and I get the following as the bottleneck (4 seconds spent on this). I am not sure what is being copying.
% in vcruntime140.dll, it looks like memcpy to me
push rdi
push rsi
mov rax, r11
mov rdi, rcx
mov rcx, r8
mov rsi, r10
rep movsb byte ptr [rdi], byte ptr [rsi]
pop rsi
pop rdi
ret
In my full program, this slowdown happens more consistently. I am still coding my program. Within 1 hour of development and testing, this slowdown usually happens. It disappears when I restart the matlab.
In the toy program above, I am only able to trigger this once for now.
My main question is why?
Observations:
- When the program is slow, the cost of "o.x(1,1)=1;" seems linear to the size of o.x.
- When the program is slow, recreating the object by "o = SlowClass()" does not help.
- If I have two identical class file, one class is slow doesn't imply another class is slow.
- After clear all, the program is fast again.
4 Kommentare
Matt J
am 3 Jan. 2022
How is it possible for o.x to be 3000 x 3000? Your append function only adds columns, not rows.
Antworten (1)
Matt J
am 3 Jan. 2022
Bearbeitet: Matt J
am 3 Jan. 2022
When the program is slow, the cost of "o.x(1,1)=1;" seems linear to the size of o.x.
Naturally. Every time you append to x, the original copy of x is destroyed and rebuilt, which involves a number of operations proportional to the size of x. It doesn't matter that you have >40GB. It only matters how long it takes for the original x to be copied.
2 Kommentare
Siehe auch
Kategorien
Mehr zu Performance and Memory finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!