diff --git a/src/tests.c b/src/tests.c index b0c4ce5..165a2de 100644 --- a/src/tests.c +++ b/src/tests.c @@ -25,13 +25,28 @@ struct test_params { char *filename; uint8_t *buffer; uint64_t byte_count; + + bool inner_malloc; }; struct testcase { char *name; test_cb cb; + bool inner_malloc; }; +void handle_buffer_malloc(struct test_params *params) { + if (params->inner_malloc) { + params->buffer = malloc(sizeof(uint8_t) * params->byte_count); + } +} + +void handle_buffer_free(struct test_params *params) { + if (params->inner_malloc) { + free(params->buffer); + } +} + void test_fread(struct repetition_tester *tester, void *user) { struct test_params *params = user; @@ -41,6 +56,8 @@ void test_fread(struct repetition_tester *tester, void *user) return; } + handle_buffer_malloc(params); + repetition_time_start(tester); int result = fread(params->buffer, params->byte_count, 1, f); repetition_time_end(tester); @@ -52,6 +69,7 @@ void test_fread(struct repetition_tester *tester, void *user) repetition_count_bytes(tester, params->byte_count); err: + handle_buffer_free(params); fclose(f); } @@ -64,6 +82,8 @@ void test_read(struct repetition_tester *tester, void *user) return; } + handle_buffer_malloc(params); + repetition_time_start(tester); int result = read(fd, params->buffer, params->byte_count); repetition_time_end(tester); @@ -75,6 +95,7 @@ void test_read(struct repetition_tester *tester, void *user) repetition_count_bytes(tester, result); err: + handle_buffer_free(params); close(fd); } @@ -87,16 +108,12 @@ int main() char *filename = "data_10000000.json"; uint64_t file_size = get_file_size(filename); - uint8_t *buffer = malloc(sizeof(uint8_t) * file_size); - struct test_params params = { - .filename = filename, - .buffer = buffer, - .byte_count = file_size - }; struct testcase cases[] = { - { .name = "fread", .cb = test_fread }, - { .name = "read", .cb = test_read }, + { .name = "read inner malloc", .cb = test_read, .inner_malloc = true }, + { .name = "read outer malloc", .cb = test_read, .inner_malloc = false }, + { .name = "fread inner malloc", .cb = test_fread, .inner_malloc = true }, + { .name = "fread outer malloc", .cb = test_fread, .inner_malloc = false }, }; struct repetition_results results = { 0 }; @@ -104,16 +121,31 @@ int main() for (int i = 0; i < ARRAY_LEN(cases); i++) { struct testcase *testcase = &cases[i]; + uint8_t *buffer = NULL; + if (!testcase->inner_malloc) { + buffer = malloc(sizeof(uint8_t) * file_size); + } + + struct test_params params = { + .filename = filename, + .buffer = buffer, + .byte_count = file_size, + .inner_malloc = testcase->inner_malloc + }; + + if (repetition_test_run(&tester, file_size, &results, testcase->cb, ¶ms)) { return -1; } printf("----- %s -----\n", testcase->name); print_repetition_results(&tester, &results); printf("\n"); + + if (!testcase->inner_malloc) { + free(buffer); + } } } - free(buffer); - return 0; }