Skip to content

Instantly share code, notes, and snippets.

@JackyYin
Created October 24, 2021 13:13
Show Gist options
  • Save JackyYin/87d8c49bb7f1eae9a28ae99a03ad3a6b to your computer and use it in GitHub Desktop.
Save JackyYin/87d8c49bb7f1eae9a28ae99a03ad3a6b to your computer and use it in GitHub Desktop.
Test L1 cache in raspi 4.
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#define L1_CACHE_SZ (32 * 1024)
#define L2_CACHE_SZ (1024 * 1024)
#define TESTOBJ sx
#define VLEN ((L2_CACHE_SZ / sizeof(TESTOBJ)) * 2)
typedef struct x {
int a;
float b;
} sx;
typedef struct y {
int a;
float b;
double c[8];
// 8 + 8 * 8 = 72 bytes
} sy;
void test_stack()
{
TESTOBJ *arr = malloc(sizeof(TESTOBJ) * VLEN);
for (int i = 0; i < VLEN; i++) {
TESTOBJ o = { .a = 0, .b = 0.0 };
arr[i] = o;
}
int itmp;
float ftmp;
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
for (int i = 0; i < VLEN; i++) {
itmp = arr[i].a;
ftmp = arr[i].b;
}
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
unsigned long elapsed_ns = (end.tv_sec - start.tv_sec) * 1000 * 1000 * 1000 + (end.tv_nsec - start.tv_nsec);
printf("stack total: %lu\n", elapsed_ns);
}
void test_heap()
{
TESTOBJ **arr = malloc(sizeof(TESTOBJ*) * VLEN);
for (int i = 0; i < VLEN; i++) {
TESTOBJ *xptr = malloc(sizeof(TESTOBJ));
arr[i] = xptr;
}
int itmp;
float ftmp;
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
for (int i = 0; i < VLEN; i++) {
itmp = arr[i]->a;
ftmp = arr[i]->b;
}
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
unsigned long elapsed_ns = (end.tv_sec - start.tv_sec) * 1000 * 1000 * 1000 + (end.tv_nsec - start.tv_nsec);
printf("heap total: %lu\n", elapsed_ns);
}
int main() {
test_stack();
test_heap();
}
@JackyYin
Copy link
Author

JackyYin commented Oct 24, 2021

test output (rpi 4):

stack total: 2498611
heap total: 3569907

@JackyYin
Copy link
Author

test output (macOS x86_64):

stack total: 655048
heap total: 2216167

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment