Saturday, June 18, 2011

Matlab Parallel loop: parfor

If we are in the situations with simple large loop even in a single CPU, using parfor is better than ordinary loop in some cases... it will enhance the efficiency dramatically. When the loop number is small, for will definitely win as the parallel command will cost time. But when the N is large, parloop will run. A good thing is to make the test to optimize the program.

s1 = 0.0; s2 = 0.0;  for j = 1:100  N = 10000;  clear A tic;   parfor i = 1:N    A(i) = exp(log(i)); end final = toc ;    s1 = s1 + final;  clear A tic;  for i = 1:N    A(i)= exp(log(i)); end final = toc;    s2 = s2+ final;  end    fprintf(1,'parfor loop runs %12.6f seconds\n',s1);   fprintf(1,'normal loop runs %12.6f seconds\n',s2); 

N=10000;
parfor loop runs 2.149823 seconds
normal loop runs 17.243006 seconds

N = 100;
parfor loop runs 0.296427 seconds
normal loop runs 0.017778 seconds


Of course, the results will be difference when we use the matlabpool open to make actual parallel run. It will depend on the overhead....


No comments: