From bfd51c23c206c802d32784ef65586a47ef84a2dd Mon Sep 17 00:00:00 2001 From: Intel A80486DX2-66 Date: Sat, 24 Feb 2024 12:02:14 +0300 Subject: [PATCH] C: add static-vs-dynamic-mem-alloc.c --- .../experiments/static-vs-dynamic-mem-alloc.c | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 c-programming/experiments/static-vs-dynamic-mem-alloc.c diff --git a/c-programming/experiments/static-vs-dynamic-mem-alloc.c b/c-programming/experiments/static-vs-dynamic-mem-alloc.c new file mode 100644 index 0000000..a83782a --- /dev/null +++ b/c-programming/experiments/static-vs-dynamic-mem-alloc.c @@ -0,0 +1,80 @@ +/* + * static-vs-dynamic-mem-alloc.c + * + * Author: Intel A80486DX2-66 + * License: Creative Commons Zero 1.0 Universal + */ + +#include +#include +#include +#include + +#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; +}