4 ms·
Begone troll. (Edit: because I noticed this too, and it got me curious, the reason for the incorrect result is that I didn't check the result of the read() cal
by ninkendo 3y ago
Begone troll.
(Edit: because I noticed this too, and it got me curious, the reason for the incorrect result is that I didn't check the result of the read() call, and it was actually reading fewer bytes, by a small handful. read() is allowed to do this, and it's up to callers to call it again. It was reading 2147479552 bytes when the file size was 2147483648 bytes. If anything this should have made the read implementation faster, but mmap still wins even though it read more bytes. A fixed version follows, and now produces the same "sum" as the mmap):
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int fd;
struct stat sb;
ssize_t s;
ssize_t read_result;
ssize_t bytes_read;
char *read_buffer;
fd = open("./bigfile", O_RDONLY);
fstat(fd, &sb); // get the size
// do the read
read_buffer = malloc(sb.st_size);
bytes_read = 0;
do {
read_result = read(fd, read_buffer + bytes_read, sb.st_size - bytes_read);
bytes_read += read_result;
} while (read_result != 0);
uint8_t sum;
// Ensure the whole buffer is touched by doing a dumb math operation on every byte
for (size_t i = 0; i < sb.st_size; ++i) {
sum += read_buffer[i]; // overflow is fine, sorta a dumb checksum
}
fprintf(stderr, "done! sum=%d", sum);
}
- geocar 3y ago> because I noticed this too When it was pointed out to you. Maybe if you read what I wrote and try benchmarking what I am saying you will “notice” more of your errors.