Simple Benchmark for Matrix Initialization
Content |
For the benchmark we will use function walltime as a black box. As the function name suggest it simple returns the wall time.
Exercise
-
Make yourself familiar with the following benchmark test:
-
In function main we allocate memory for different matrix dimensions.
-
For each matrix we measure the wall time needed to initialize the matrix.
-
We compare the times for matrices that are either store row major or col major
-
-
Compile and run the benchmark. Use different optimization flags:
-
No optimization
-
-O1, -O2, -O3 and -Ofast
-
#include <math.h> // for nan() #include <stddef.h> // for size_t, ptrdiff_t #include <stdio.h> // for printf #include <stdlib.h> // for malloc(), free() #include <sys/times.h> // needed for walltime() #include <unistd.h> // needed for walltime() //-- Function for benchmarking and testing ------------------------------------- double walltime() { struct tms ts; static double ClockTick=0.0; if (ClockTick==0.0) { ClockTick = 1.0 / ((double) sysconf(_SC_CLK_TCK)); } return ((double) times(&ts)) * ClockTick; } //------------------------------------------------------------------------------ void initGeMatrix(size_t m, size_t n, double *A, ptrdiff_t incRowA, ptrdiff_t incColA) { for (size_t i=0; i<m; ++i) { for (size_t j=0; j<n; ++j) { A[i*incRowA + j*incColA] = i*n + j +1; } } } int main() { printf("#%5s %5s %10s %10s\n", "m", "n", "t (colm)", "t (rowm)"); for (size_t m=100, n=100; m<=7000 && n<=7000; m+=100, n+=100) { printf(" %5ld %5ld ", (long)m, (long)n); // bench initialization for row major matrix { ptrdiff_t incRowA = n; ptrdiff_t incColA = 1; double *A = malloc(m*n*sizeof(double)); if (!A) { abort(); } double t = walltime(); initGeMatrix(m, n, A, incRowA, incColA); t = walltime() - t; printf("%10.2lf ", t); free(A); } // bench initialization for col major matrix { ptrdiff_t incRowA = 1; ptrdiff_t incColA = m; double *A = malloc(m*n*sizeof(double)); if (!A) { abort(); } double t = walltime(); initGeMatrix(m, n, A, incRowA, incColA); t = walltime() - t; printf("%10.2lf ", t); free(A); } printf("\n"); } }
Exercise
-
Modify the algorithm for initGeMatrix as follows:
if A is store row major then initialize matrix A row wise else initialize matrix A column wise
-
Re-run the benchmark with the different optimization flags.