% Parallel server check;
% Problem set up;
primeNumbers = primes(uint64(2^19));
compositeNumbers = primeNumbers.*primeNumbers(randperm(numel(primeNumbers)));
factors = zeros(numel(primeNumbers),2);
% No parallelization;
disp("No parallelization")
tic;
for idx = 1:numel(compositeNumbers)
    factors(idx,:) = factor(compositeNumbers(idx));
end
toc
%% 
factors = zeros(numel(primeNumbers),2);
% Default parallelization;
disp("Default parallelization, one iteration")
tic;
parfor idx = 1:numel(compositeNumbers)
    factors(idx,:) = factor(compositeNumbers(idx));
end
toc
delete(gcp('nocreate'))

%% 
factors = zeros(numel(primeNumbers),2);
% Parallel cores on one server;
disp("Multicore single node parallelization, 1 to 12 cores")
parpool('Processes',12);
numWorkers = [1 2 4 6 12];
tLocal = zeros(size(numWorkers));
for w = 1:numel(numWorkers)
    factors = zeros(numel(primeNumbers),2);
    tic;
    parfor (idx = 1:numel(compositeNumbers), numWorkers(w))
        factors(idx,:) = factor(compositeNumbers(idx));
    end
    tLocal(w) = toc;
end
tLocal
delete(gcp('nocreate'))

%% 
% Parallel servers;
parpool('2gb short',12);

numWorkers = [1 2 4 8 12];
tCluster = zeros(size(numWorkers));

for w = 1:numel(numWorkers)
    factors = zeros(numel(primeNumbers),2);
    tic;
    parfor (idx = 1:numel(compositeNumbers), numWorkers(w))
        factors(idx,:) = factor(compositeNumbers(idx));
    end
    tCluster(w) = toc;
end
tCluster
delete(gcp('nocreate'))
