Skip to content

Instantly share code, notes, and snippets.

@maxsei
Created April 2, 2023 19:06
Show Gist options
  • Select an option

  • Save maxsei/2810eec6a1c9f955b716fa678c1a99c5 to your computer and use it in GitHub Desktop.

Select an option

Save maxsei/2810eec6a1c9f955b716fa678c1a99c5 to your computer and use it in GitHub Desktop.
program that trys but fails to demonstrate cache locality (c learning)
/* gcc -o out main.c && ./out */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct {
int x;
int y;
} Point;
/*
* [xyxyxyxyxyxyxyxy]
*/
typedef struct {
int *x;
int *y;
} PointColumns;
/*
* [xxxxxxxxyyyyyyyy]
*/
// CPU registers tiny
// lvl 1 cache smol
// lvl 2 cache small
// lvl 3 cache medium
// main memory large+slow
// disk massive+slow
#define COUNT 10
int main() {
// Intialize records.
Point *records10 = (Point *)malloc(sizeof(Point) * COUNT);
for (int i = 0; i < COUNT; i++) {
records10[i].x = i * 2;
records10[i].y = i * 4;
}
for (int i = 0; i < COUNT; i++) {
printf("%03d: x = %d y = %d\n", i, records10[i].x, records10[i].y);
}
// Intialize columns
PointColumns columns10;
columns10.x = (int *)malloc(sizeof(int) * COUNT);
columns10.y = (int *)malloc(sizeof(int) * COUNT);
for (int i = 0; i < COUNT; i++) {
columns10.x[i] = i * 2;
columns10.y[i] = i * 4;
}
for (int i = 0; i < COUNT; i++) {
printf("%03d: x = %d y = %d\n", i, columns10.x[i], columns10.y[i]);
}
// Time increment x by 1 (records)
{
clock_t start, end;
double cpu_time_used;
for (int i = 0; i < COUNT; i++)
records10[i].x += 1;
start = clock();
end = clock();
cpu_time_used = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("records took: %f\n", cpu_time_used);
}
// Time increment x by 1 (columns)
{
clock_t start, end;
double cpu_time_used;
for (int i = 0; i < COUNT; i++)
columns10.x[i] += 1;
start = clock();
end = clock();
cpu_time_used = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("columns took: %f\n", cpu_time_used);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment