From 551933cddd6e0af73b739f2ef060c823ff6a85a0 Mon Sep 17 00:00:00 2001 From: Intel A80486DX2-66 Date: Mon, 29 Jan 2024 19:07:06 +0300 Subject: [PATCH] C: mem. for audio: optimize; use the same function Memory allocation for the audio buffer: 1. Instant mode: Use `malloc` instead of `calloc` 2. Allocate heap memory before the loop to speed up audio generation, free the memory after the loop 3. Extract the memory allocation into a macro --- src/template.c | 41 ++++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/src/template.c b/src/template.c index 09818b7..1220890 100644 --- a/src/template.c +++ b/src/template.c @@ -52,6 +52,17 @@ const char* ANSI_CLEAR = __ANSI_CLEAR_STRING; #define unsigned_to_signed(x) (x - PCM_COEFFICIENT) #define signed_to_unsigned(x) (x + PCM_COEFFICIENT) +// macros +#define ALLOCATE_MEMORY(nmemb) \ + SAMPLE_TYPE* buffer = malloc( \ + (size_t) nmemb * sizeof(SAMPLE_TYPE) \ + ); \ + \ + if (buffer == NULL) { \ + perror("malloc"); \ + return EXIT_FAILURE; \ + } + // global variables #define SILENT_MODE `silent_mode` #define VERBOSE_MODE `verbose_mode` @@ -198,28 +209,24 @@ main(void) } const size_t MAX = (PRODUCT + (BLOCK_SIZE - 1)) / BLOCK_SIZE; +#endif + // * allocate heap for sample data +#if SEQUENTIAL_MODE + size_t calc_block_size = BLOCK_SIZE; + ALLOCATE_MEMORY(calc_block_size) +#else + ALLOCATE_MEMORY(PRODUCT) +#endif + +#if SEQUENTIAL_MODE size_t w = 0; for (size_t seq = 0; seq < MAX; seq++) { - size_t calc_block_size = BLOCK_SIZE; if ((w + BLOCK_SIZE) >= PRODUCT) calc_block_size = PRODUCT - w; #else do { #endif - // * allocate heap for sample data - SAMPLE_TYPE* buffer = -#if SEQUENTIAL_MODE - malloc((size_t) calc_block_size * -#else - calloc(PRODUCT, -#endif - sizeof(SAMPLE_TYPE)); - - if (buffer == NULL) { - perror("calloc"); - return 1; - } // * bytebeat generating loop const uintmax_t product_minus_1 = PRODUCT - 1, @@ -324,14 +331,14 @@ main(void) #if SEQUENTIAL_MODE fflush(output_file); #endif - - // * free allocated heap - free(buffer); } #if !SEQUENTIAL_MODE while (0); #endif + // * free allocated heap + free(buffer); + // 6. close file fclose(output_file);