Skip to content

Instantly share code, notes, and snippets.

@thewisenerd
Created August 17, 2023 02:57
Show Gist options
  • Save thewisenerd/3e22299f9f4eef4270fa7679fe1398b5 to your computer and use it in GitHub Desktop.
Save thewisenerd/3e22299f9f4eef4270fa7679fe1398b5 to your computer and use it in GitHub Desktop.
#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#define ONE_MB (1024 * 1024)
#define SLEEP_BUF_DEFAULT 16 // wait 1s every N MB
#define SLEEP_BUF_MIN 0
#define SLEEP_BUF_MAX (1024 * 1024) // surely nobody has 1 TB lying around
#define SLEEP_ITER_ENV "SLEEP_ITER"
int main(int argc, char* argv[]) {
const int page_sz = getpagesize();
printf("page_sz=%d\n", page_sz);
assert(page_sz > 0);
// page size is going to be either 4K or 16K
const int per_mb = ONE_MB / page_sz;
printf("per_mb=%d\n", per_mb);
assert(per_mb > 0);
char *pTmp;
int sleep_buf;
if (( pTmp = getenv( "SLEEP_ITER" )) != NULL ) {
sleep_buf = atoi(pTmp);
} else {
sleep_buf = SLEEP_BUF_DEFAULT;
}
sleep_buf = sleep_buf < SLEEP_BUF_MIN ? SLEEP_BUF_MIN : (sleep_buf > SLEEP_BUF_MAX ? SLEEP_BUF_MAX : sleep_buf);
size_t mb_count = 0;
char *block;
while (1) {
block = (char*) calloc(1, ONE_MB);
mb_count++;
printf("alloc: %zu MB\n", mb_count);
for (int page = 0; page < per_mb; page++) {
block[page*page_sz] = (page % 2) ? 'A' : '!';
}
printf("touch: %zu MB\n", mb_count);
if (sleep_buf && mb_count % sleep_buf == 0) {
sleep(1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment