Last active
December 5, 2017 23:12
-
-
Save adyp/4db6f1cb75be385700b0647f61959628 to your computer and use it in GitHub Desktop.
Memory allocator tester
This file contains 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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
#define DEFAULT_UNIT 1024*1024 /* 1Mb */ | |
size_t alloc_unit; | |
char* format_size(unsigned long int); | |
int main(int argc, char **argv) { | |
unsigned long int counter, alloc_count; | |
void *p; | |
int opt, write_mode; | |
float write_rate; | |
alloc_count = 0; | |
alloc_unit = DEFAULT_UNIT; | |
write_mode = 0; | |
write_rate = 1; | |
while ((opt = getopt(argc, argv, "c:r:u:w")) != -1) { | |
switch (opt) { | |
case 'c': | |
alloc_count = atol(optarg); | |
break; | |
case 'u': | |
alloc_unit = atoi(optarg) * 1024; | |
break; | |
case 'w': | |
write_mode = 1; | |
break; | |
case 'r': | |
write_rate = atof(optarg); | |
break; | |
case '?': | |
printf("There was an error processing the arguments\n\n"); | |
default: | |
printf("Usage:\n\n"); | |
printf(" %s [ -u <N> ] [-w]\n\n", argv[0]); | |
printf("-u set allocation unit to <N> (in Kb)\n"); | |
printf("-w write to the allocate memory\n\n"); | |
return 100; | |
} | |
} | |
printf("INFO: allocation unit: %s\n", format_size(1)); | |
printf("INFO: allocation limit: %s\n", alloc_count ? format_size(alloc_count) : "none"); | |
printf("INFO: write mode is %s\n", write_mode ? "enabled" : "disabled"); | |
printf("INFO: write rate is %.2f\n", write_rate); | |
printf("\n\n"); | |
for (counter = 0; !alloc_count || counter < alloc_count; counter++) { | |
p = malloc(alloc_unit); | |
if (p == NULL) { | |
printf("\n\nMemory allocation failed -- aborting\n"); | |
return 10; | |
} | |
printf("\rAllocated: %s ", format_size(counter)); | |
if (write_mode) { | |
memset(p, 'X', alloc_unit * write_rate); | |
} | |
} | |
return 0; | |
} | |
char* format_size(unsigned long int cnt) { | |
static const char *SIZES[] = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; | |
size_t div = 0; | |
size_t rem = 0; | |
int divisions; | |
size_t msize; | |
static char msg[1000]; | |
msize = cnt*alloc_unit; // we count in allocation units ! | |
divisions = sizeof(SIZES) / sizeof(*SIZES); | |
while (msize >= 1024 && div < divisions) { | |
rem = (msize % 1024); | |
msize /= 1024; | |
div++; | |
} | |
sprintf(msg, "%3.2f %s", (float)msize + (float)rem / 1024.0, SIZES[div]); | |
return msg; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compile:
Use: