Skip to content

Instantly share code, notes, and snippets.

@bcho
Created November 26, 2014 05:20
Show Gist options
  • Select an option

  • Save bcho/22ce746663297183b039 to your computer and use it in GitHub Desktop.

Select an option

Save bcho/22ce746663297183b039 to your computer and use it in GitHub Desktop.
trick
// Locality test.
//
// See:
// http://en.wikipedia.org/wiki/Locality_of_reference#Matrix_multiplication
#include <string.h>
#define N 1000
int a[N][N], b[N][N], c[N][N];
void m1()
{
int i, j, k;
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
for (k = 0; k < N; k++)
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
void m2()
{
int i, j, k;
for (i = 0; i < N; i++)
for (k = 0; k < N; k++) // <- b[k][j] can be cached.
for (j = 0; j < N; j++)
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
int main(int argc, char *argv[])
{
int i, j;
memset(c, 0, N * N);
for (i = 0; i < N; i++)
for (j = 0; j < N; j++) {
a[i][j] = 3;
b[i][j] = 5;
}
if (argc > 1 && argv[1][0] == '1')
m1();
else
m2();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment