1
0
repetition-testing/src/main_read_file.c

85 lines
2.2 KiB
C

#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include "utils.c"
#include "repetition_tester.c"
void read_file_with_fread(struct repetitor *repetitor, uint8_t *buffer, uint64_t buffer_size, char *filename) {
FILE *file = fopen(filename, "r");
uint64_t read_amount = 0;
while (read_amount < buffer_size) {
repetitor_measure_start(repetitor);
int result = fread(&buffer[read_amount], 1, buffer_size - read_amount, file);
repetitor_measure_stop(repetitor, result > 0 ? result : 0);
if (result <= 0) {
printf("ERROR: Failed to read from file\n");
break;
}
read_amount += result;
}
fclose(file);
}
void read_file_with_read(struct repetitor *repetitor, uint8_t *buffer, uint64_t buffer_size, char *filename) {
int file = open(filename, O_RDONLY);
uint64_t read_amount = 0;
while (read_amount < buffer_size) {
repetitor_measure_start(repetitor);
int result = read(file, &buffer[read_amount], buffer_size - read_amount);
repetitor_measure_stop(repetitor, result > 0 ? result : 0);
if (result <= 0) {
printf("ERROR: Failed to read from file\n");
break;
}
read_amount += result;
}
close(file);
}
int main_test_read_file(char *filename) {
typedef void (*read_file_b)(struct repetitor *repetitor, uint8_t *buffer, uint64_t buffer_size, char *filename);
struct testcase {
char *name;
read_file_b cb;
};
struct testcase cases[] = {
{ .name = "read()", .cb = read_file_with_read },
{ .name = "fread()", .cb = read_file_with_fread },
};
struct repetitor repetitor = {};
repetitor_init(&repetitor);
printf("CPU Frequency: %ldHz (~%.2fGHz)\n", repetitor.cpu_freq, (float)repetitor.cpu_freq/(1000*1000*1000));
uint64_t file_size = get_file_size(filename);
uint8_t *buffer = malloc(sizeof(uint8_t) * file_size);
while (repeat_cycle_times(&repetitor, 3)) {
for (int i = 0; i < ARRAY_LEN(cases); i++) {
struct testcase *testcase = &cases[i];
repetitor_clear(&repetitor);
while (repetitor_repeat(&repetitor, 1)) {
repetitor_start(&repetitor);
testcase->cb(&repetitor, buffer, file_size, filename);
repetitor_stop(&repetitor);
}
repetitor_print_results_label(&repetitor, testcase->name);
}
}
return 0;
}