Skip to content

Instantly share code, notes, and snippets.

@kostja
Created August 17, 2017 13:55
Show Gist options
  • Save kostja/ea06e922db6f1bd3dafffc0f533d96f3 to your computer and use it in GitHub Desktop.
Save kostja/ea06e922db6f1bd3dafffc0f533d96f3 to your computer and use it in GitHub Desktop.
malloc of large objects
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
enum {
ALLOC_STREAK_MAX = 1024,
ALLOC_MIN = 1024 * 1024,
ALLOC_MAX = 1024 * 1024 * 128,
ITERATIONS = 1024,
};
int allocations = 0;
void *ptrs[ALLOC_STREAK_MAX];
size_t sizes[ALLOC_STREAK_MAX];
void
streak(int n_allocs)
{
for (int i = 0; i < n_allocs; i++) {
int size = rand() % ALLOC_MAX;
if (size < ALLOC_MIN)
size += ALLOC_MIN;
sizes[i] = size;
ptrs[i] = malloc(size);
allocations++;
}
for (int i = 0; i < n_allocs; i++) {
free(ptrs[i]);
}
}
int main()
{
int seed = time(NULL);
printf("seed: %d\n", seed);
srand(seed);
for (int i = 0; i < ITERATIONS; i++)
streak(rand() % ALLOC_STREAK_MAX);
printf("total allocations: %d\n", allocations);
}
kostja@atlas ~ % time ./a.out
seed: 1502978000
total allocations: 509347
./a.out 0,46s user 6,86s system 99% cpu 7,314 total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment