How can we reduce the execution time of this whole code?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Sadiq Akbar
el 8 de Feb. de 2023
Comentada: Sadiq Akbar
el 8 de Feb. de 2023
I want to minimize the "execution time" of the code given in the attachment. You can run the m file "main".
2 comentarios
Dyuman Joshi
el 8 de Feb. de 2023
In myfunction, Why are you pre-allocating an empty matrix?
K = length(u); %Constant4
c=zeros(M*N, length(u)-K);
ce=zeros(M*N, length(u)-K);
%Modify it as
c=zeros(M*N,K);
ce=zeros(M*N,K);
And club the two for loop together -
for g= 1:K
c(:,g)=kron(a(:,g),f(:,g));
end
for g= 1:K
ce(:,g)=kron(ae(:,g),fe(:,g));
end
into
for g = i %i is already defined in the code
c(:,g)=kron(a(:,g),f(:,g));
ce(:,g)=kron(ae(:,g),fe(:,g));
end
Additionally, pre-allocate Sol and Fitness in fp1
After these changes, the code runs in 2.5674 secs in i3-5th gen, 8gb RAM, which imo is fast enough.
Respuesta aceptada
Dyuman Joshi
el 8 de Feb. de 2023
I am aware that pre-allocation speeds up the process, but pre-allocating an empty matrix doesn't reserve any memory for the operation and it is slower than pre-allocating with a zeros matrix. See below -
Modify the pre-allocation as I have suggested above.
v=1e6;
y=zeros(v,0);
z=zeros(v,1);
whos y z
tic
for ix=1:v
y(ix)=i;
end
toc
tic
for ix=1:v
z(ix)=i;
end
toc
"But how to pre-allocate Sol and Fitness in fp1?"
It's clear from the code
%for i=1:psize
% Sol(i,:)=Lb+(Ub-Lb).*rand(1,d);
% Fitness(i)=fun(Sol(i,:));%--------------------(1)
%end
Fitness has psize elements, so size is (1xpsize, as the output of the function myfunction is a scalar value)
and Sol has psize rows and d columns.
Pre-allocate zero matrices accordingly.
3 comentarios
Dyuman Joshi
el 8 de Feb. de 2023
"I found that the time with pre-allocation is lower than without pre-allocation."
I am well aware of this. But that was not my point.
Nevertheless, what you have done now is better than what you did before.
How did you arrive at n+1 and N_iter?
Ugh. I specifically mentioned what to use for pre-allocation of Sol and Fitness -
"Fitness has psize elements, so size is (1xpsize, as the output of the function myfunction is a scalar value)
and Sol has psize rows and d columns.
Pre-allocate zero matrices accordingly. "
Use this -
Sol=zeros(psize,dim);
Fitness=zeros(psize,1);
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!