70 lines
2.1 KiB
Matlab
70 lines
2.1 KiB
Matlab
% 1. Setup Data OUTSIDE the timer
|
|
d = gpuDevice;
|
|
N = 10000;
|
|
|
|
fprintf('Preparing data...\n');
|
|
A_cpu_double = rand(N, N); % Create double on CPU
|
|
A_cpu_single = single(A_cpu_double); % Create single on CPU
|
|
|
|
% Warmup run (wakes up the GPU from idle state)
|
|
A_warm = gpuArray.rand(1000, 1000, 'single');
|
|
B_warm = A_warm * A_warm;
|
|
wait(d);
|
|
|
|
fprintf('------------------------------------------------\n');
|
|
|
|
% TEST 1: Double Precision (The "Slow" way)
|
|
% We move data to GPU first so we only measure calculation time
|
|
A_gpu_double = gpuArray(A_cpu_double);
|
|
wait(d); % Ensure transfer is done before starting timer
|
|
|
|
fprintf('Running DOUBLE precision test... ');
|
|
tic;
|
|
B_gpu = A_gpu_double * A_gpu_double;
|
|
wait(d); % FORCE MATLAB TO WAIT FOR GPU
|
|
time_double = toc;
|
|
fprintf('Done.\n');
|
|
fprintf('Double Precision Time: %.4f seconds\n', time_double);
|
|
|
|
% TEST 2: Single Precision (The "Fast" way)
|
|
A_gpu_single = gpuArray(A_cpu_single);
|
|
wait(d); % Ensure transfer is done
|
|
|
|
fprintf('Running SINGLE precision test... ');
|
|
tic;
|
|
B_gpu = A_gpu_single * A_gpu_single;
|
|
wait(d); % FORCE MATLAB TO WAIT FOR GPU
|
|
time_single = toc;
|
|
fprintf('Done.\n');
|
|
fprintf('Single Precision Time: %.4f seconds\n', time_single);
|
|
|
|
% Calculate Speedup
|
|
fprintf('------------------------------------------------\n');
|
|
fprintf('Speedup Factor using single precision: %.2fx\n', time_double / time_single);
|
|
|
|
%
|
|
% Create 10,000 small matrices (10x10) stacked in a 3D array
|
|
A_stack = gpuArray.rand(10, 10, 10000, 'single');
|
|
B_stack = gpuArray.rand(10, 10, 10000, 'single');
|
|
|
|
% BAD: Looping (GPU overhead kills you)
|
|
tic;
|
|
for i=1:10000
|
|
C(:,:,i) = A_stack(:,:,i) * B_stack(:,:,i);
|
|
end
|
|
wait(d);
|
|
loop_time = toc;
|
|
|
|
% GOOD: Pagefun (Executes all 10,000 mults simultaneously)
|
|
tic;
|
|
C_stack = pagefun(@mtimes, A_stack, B_stack);
|
|
wait(d);
|
|
pagefun_time = toc;
|
|
|
|
fprintf('------------------------------------------------\n');
|
|
fprintf('Speedup Factor using pagefun: %.2fx\n', loop_time / pagefun_time);
|
|
|
|
|
|
fprintf('Total VRAM: %.2f GB\n', d.TotalMemory / 1e9);
|
|
fprintf('Available VRAM: %.2f GB\n', d.AvailableMemory / 1e9);
|
|
fprintf('Usage: %.1f%%\n', 100 * (1 - d.AvailableMemory / d.TotalMemory)); |