1
0
mirror of https://gitlab.com/80486DX2-66/gists synced 2024-11-09 03:12:23 +05:30

C: add static-vs-dynamic-mem-alloc.c

This commit is contained in:
Intel A80486DX2-66 2024-02-24 12:02:14 +03:00
parent 3e37f5fb73
commit bfd51c23c2
Signed by: 80486DX2-66
GPG Key ID: 83631EF27054609B

View File

@ -0,0 +1,80 @@
/*
* 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 ((size_t) 268435456)
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;
}