How to run in same time as C
Mostrar comentarios más antiguos
Hi,
Below psudo code for a C program took 66 sec. Same thing i tried to do in MATLAB (please find code below) it is much slower.Is it possible to run in same time as C.Please clarify this it will be very helpful.
Thanks,
Sita
psudo code for C
for(int i=0; i < 10; i++){
x[1] = 2.0 + drand48();
//x[2] = 2.0 + drand48();
for(int j=0; j < 30; j++){
x[2] = 2.0 + drand48();
x[3] = 2.0 + drand48();
//x[4] = 2.0 + drand48();
for(int k=0; k < 60; k++){
x[4] = 2.0 + drand48();
x[5] = 2.0 + drand48();
x[6] = 2.0 + drand48();
for(int l=0; l < 80; l++){
x[7] = 2.0 + drand48();
x[8] = 2.0 + drand48();
for(int m=0; m < 100; m++){
x[9] = 2.0 + drand48();
x[10] = 2.0 + drand48();
val = calc_func(x);
if(val < min_so_far){
for(int p=1; p <= 10; p++){
best_comb[p] = x[p];
}
min_so_far = val;
}
}
}
}
}
}
MATLAB Code:
clear;
clc;
tic
countm=0;
n=1;
s=1;
for t=1:s
for i=1:10
x1=min1 + ((max1 - min1)*rand(1));
for j=1:40
x2=min2 + ((max2 - min2)*rand(1));
x3=min3 + ((max3 - min3)*rand(1));
for k=1:60
x4=min4 +((max4 - min4)*rand(1));
x5=min5 +((max5-min5)*rand(1));
x6=min6 +((max6-min6)*rand(1));
for l=1:80
x7=min7+((max7-min7)*rand(1));
x8=min8 + ((max8 - min8)*rand(1));
for m=1:100
x9=min9+((max9-min9)*rand(1));
x10=min10+((max10-min10)*rand(1));
countm=countm+1 ;
yal= fc10(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10);
minvals( countm)=min(yal);
end
end
end
end
end
minofall=min(minvals)
end
toc
Respuesta aceptada
Más respuestas (2)
David Sanchez
el 25 de Jun. de 2013
1 voto
It happens than C is much faster than Matlab. Even when Matlab is well optimized when it comes to processing speed, C is a lower level language and performs better than Matlab. Besides, if you try to use some built-in Matlab functions, you can improve your code significantly. Some other times, it just happens than you can not achieve the processing speed achieved with C code.
Jan
el 25 de Jun. de 2013
The pre-allocation is essential for the processing speed. Is minvals pre-allocated, e.g. with the maximal possible length?
Usually a one vector x with 10 elements is more efficient rhan 10 scalars.
The program calculates max9-min9 and max10-min10 192'000'000 times. Although the actual calculation is cheap, doing this repeatedly wastes time. Better:
offset = [min1, min2, min3, min4, min5, min6, min7, min8, min9];
scale = [max1, max2, max3, max4, max5, max6, max7, max8, max9] - offset;
x = zeros(1, 9);
for ...
x(1) = rand;
...
for m=1:100
x(9:10) = rand(1, 2);
x = x .* scale + offset;
yal = fc10(x);
...
But even here the whole vector x is multiplied in the inner loop. So here is still a big potential for improvements.
Categorías
Más información sobre Write C Functions Callable from MATLAB (MEX Files) en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!