Created
February 5, 2025 05:17
-
-
Save attractivechaos/875242a3abc352d1ce80659a200637ae to your computer and use it in GitHub Desktop.
Testing the performance of memory pool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// You need the following three files to compile: | |
// https://github.com/attractivechaos/klib/blob/master/kavl.h | |
// https://github.com/attractivechaos/klib/blob/master/kmempool.h | |
// https://github.com/attractivechaos/klib/blob/master/kmempool.c | |
// Compile with: gcc -O3 -Wall test.c kmempool.c -o test | |
// Run with "./test" for raw malloc and "./test m" for memory pool | |
#include <stdio.h> | |
#include <stdint.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
#include "kmempool.h" | |
#include "kavl.h" | |
typedef struct node_s { | |
uint64_t key; | |
KAVL_HEAD(struct node_s) head; | |
} node_t; | |
#define node_cmp(a, b) (((a)->key > (b)->key) - ((a)->key < (b)->key)) | |
KAVL_INIT(t, node_t, head, node_cmp) | |
uint64_t splitmix64(uint64_t *x) | |
{ | |
uint64_t z = ((*x) += 0x9e3779b97f4a7c15ULL); | |
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL; | |
z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL; | |
return z ^ (z >> 31); | |
} | |
uint64_t test_mp(void *mp, uint64_t n, uint64_t x) | |
{ | |
uint64_t i, sz; | |
node_t *root = 0, *p; | |
fprintf(stderr, "Using memory pool\n"); | |
p = (node_t*)kmp_alloc(mp); | |
for (i = 0; i < n; ++i) { | |
uint64_t z; | |
node_t *q; | |
z = splitmix64(&x); | |
p->key = z % (n>>2); | |
q = kavl_find(t, root, p, 0); | |
if (q == 0) { // present | |
kavl_insert(t, &root, p, 0); | |
p = (node_t*)kmp_alloc(mp); | |
} else { | |
q = kavl_erase(t, &root, q, 0); | |
kmp_free(mp, q); | |
} | |
} | |
kmp_free(mp, p); | |
sz = kavl_size(head, root); | |
return sz; | |
} | |
uint64_t test_raw(uint64_t n, uint64_t x) | |
{ | |
uint64_t i, sz; | |
node_t *root = 0, *p; | |
fprintf(stderr, "Using raw malloc\n"); | |
p = (node_t*)malloc(sizeof(node_t)); | |
for (i = 0; i < n; ++i) { | |
uint64_t z; | |
node_t *q; | |
z = splitmix64(&x); | |
p->key = z % (n>>2); | |
q = kavl_find(t, root, p, 0); | |
if (q == 0) { // present | |
kavl_insert(t, &root, p, 0); | |
p = (node_t*)malloc(sizeof(node_t)); | |
} else { | |
q = kavl_erase(t, &root, q, 0); | |
free(q); | |
} | |
} | |
free(p); | |
sz = kavl_size(head, root); | |
kavl_free(node_t, head, root, free); | |
return sz; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
int n = 10000000; | |
uint64_t x = 11, sz; | |
if (argc > 1) { | |
void *mp = kmp_init(sizeof(node_t)); | |
sz = test_mp(mp, n, x); | |
kmp_destroy(mp); | |
} else { | |
sz = test_raw(n, x); | |
} | |
printf("%ld\n", (long)sz); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment