title: Matlab's fftn gets slower with multithreading?
body: <p>I have access to a 12 core machine and some matlab code that relies heavily on fftn. I would like to speed up my code.</p>
  
  <p>Since the fft can be parallelized I would think that more cores would help but I'm seeing the opposite.</p>
  
  <p>Here's an example:</p>
  
  <pre><code>X = peaks(1028);
  
  ncores = feature('numcores');
  ntrials = 20;
  
  mtx_power_times = zeros(ncores,ntrials);
  fft_times = zeros(ncores, ntrials);
  
  for i=1:ncores
      for j=1:ntrials
  
          maxNumCompThreads(i);
  
          tic;
          X^2;
          mtx_power_times(i,j) = toc;
  
          tic
          fftn(X);
          fft_times(i,j) = toc;
  
      end
  end
  
  subplot(1,2,1);
  plot(mtx_power_times,'x-')
  title('mtx power time vs number of cores');
  
  subplot(1,2,2);
  plot(fft_times,'x-');
  title('fftn time vs num of cores');
  </code></pre>
  
  <p>Which gives me this:
  <img src="https://i.stack.imgur.com/UGXad.png" alt="Timing results for matrix multiplication and fftn"></p>
  
  <p>The speedup for matrix multiplication is great but it looks like my ffts go almost 3x slower when I use all my cores. What's going on?</p>
  
  <p>For reference my version is 7.12.0.635 (R2011a)</p>
  
  <p><strong>Edit:</strong> On large 2D arrays taking 1D transforms I get the same problem:
  <img src="https://i.stack.imgur.com/9E1oI.png" alt="enter image description here"></p>
  
  <p><strong>Edit:</strong> The problem appears to be that fftw is not seeing the thread limiting that maxNumCompThreads enforces. I'm getting all the cpus going full speed no matter what I set maxNumCompThreads at.</p>
  
  <p><img src="https://i.stack.imgur.com/FMa7F.png" alt="enter image description here"></p>
  
  <p>So... is there a way I can specify how many processors I want to use for an fft in Matlab?</p>
  
  <p><strong>Edit:</strong> Looks like I can't do this without some careful work in .mex files. <a href="http://www.mathworks.com/matlabcentral/answers/35088-how-to-control-number-of-threads-in-fft" rel="nofollow noreferrer">http://www.mathworks.com/matlabcentral/answers/35088-how-to-control-number-of-threads-in-fft</a> has an answer. It would be nice if someone has an easy fix...</p>