%
% simple finite difference example
%

close all; clear all

N = 1000;

gpu = gpuDevice;

for pass = 1:4
  if pass==1
    A = ones(N,'single');           % CPU pass
    q = single(0.25);
  elseif pass==2
    A = gpuArray.ones(N,'single');  % GPU pass
    q = single(0.25);
  elseif pass==3
    A = ones(N);                    % CPU pass
    q = 0.25;
  elseif pass==4
    A = gpuArray.ones(N);           % GPU pass
    q = 0.25;
  end

  A(1:N-1:N,:) = 0;
  A(:,1:N-1:N) = 0;

  i = 2:N-1;
  j = 2:N-1;

  tic                               % start timing
  for iter = 1:1000
    A(i,j) = q * (A(i-1,j) + A(i+1,j) + A(i,j-1) + A(i,j+1));
  end

  if pass==1                 % CPU pass
    fprintf('CPU (single): execution time = %f \n',toc)
  elseif pass==2             % GPU pass
    wait(gpu);               % wait to ensure it has finished
    fprintf('GPU (single): execution time = %f \n',toc)
  elseif pass==3             % CPU pass
    fprintf('CPU (double): execution time = %f \n',toc)
  elseif pass==4             % GPU pass
    wait(gpu);               % wait to ensure it has finished
    fprintf('GPU (double): execution time = %f \n',toc)
  end
end
