1
0
mirror of https://gitlab.com/80486DX2-66/gists synced 2024-12-27 14:50:23 +05:30
gists/c-programming/experiments/static-vs-dynamic-mem-alloc.c

81 lines
1.8 KiB
C

/*
* static-vs-dynamic-mem-alloc.c
*
* Author: Intel A80486DX2-66
* License: Creative Commons Zero 1.0 Universal
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MULTIPLIER 268435456ULL
void empty(uint8_t** mem);
void static_memory_allocation(uint8_t** mem);
void dynamic_memory_allocation(uint8_t** mem);
long double measure(void (*function)(uint8_t**), long double* c);
void empty(uint8_t** mem) {
return;
}
void static_memory_allocation(uint8_t** mem) {
*mem = malloc(MULTIPLIER * sizeof(uint8_t));
if (*mem == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
}
void dynamic_memory_allocation(uint8_t** mem) {
*mem = malloc(1 * sizeof(uint8_t));
if (*mem == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
for (size_t i = 1; i < MULTIPLIER; i++) {
uint8_t* new_memory = realloc(*mem, i * sizeof(uint8_t));
if (new_memory == NULL) {
perror("realloc");
exit(EXIT_FAILURE);
}
*mem = new_memory;
}
}
long double measure(void (*function)(uint8_t**), long double* c) {
clock_t start;
start = clock();
uint8_t* ptr = NULL;
function(&ptr);
if (ptr != NULL)
free(ptr);
clock_t end = clock();
long double cpu_time_used = ((long double) (end - start) * 1000000000.l) /
CLOCKS_PER_SEC;
if (c != NULL) {
cpu_time_used -= *c;
printf(": ~%.0Lf nanoseconds\n", cpu_time_used);
}
return cpu_time_used;
}
int main(void) {
long double c = measure(empty, NULL); // empty function call
printf(" Static memory allocation");
long double value1 = measure(static_memory_allocation, &c);
printf("Dynamic memory allocation");
long double value2 = measure(dynamic_memory_allocation, &c);
printf("\nStatic memory allocation is ~%.0Lf nanoseconds faster",
value2 - value1);
return EXIT_SUCCESS;
}