问题
I want to know the difference between
char *text = (char *)malloc(4096);
memset(text, 'a', 4096);
int fd = open(filepath, O_RDWR | O_CREAT | O_DIRECT);
for(int i=0; i<1000; i++) {
write(fd, (void *)text, 4096);
fsync(fd);
}
close (fd);
and
char *text = (char *)malloc(4096);
memset(text, 'a', 4096);
int fd = open(filepath, O_RDWR | O_CREAT | O_DIRECT | O_SYNC); //<----Difference
for(int i=0; i<1000; i++) {
write(fd, (void *)text, 4096);
// fsync(fd); <--------------------------------------------------Difference
}
close (fd);
The performance of the code above is way slower than that below.
回答1:
On the one hand there shouldn't be any difference because a similar amount of work has to happen in both cases (write then disk flush assuming no chicanery). On the other hand, the first case has to do twice as many syscalls so (in theory) has more overhead (especially if time it takes to make the syscall is a significant part of total time it takes to do the operation). In all probability it likely depends on the disk/kernel/CPU/size of I/O etc. as to whether there is a difference between the two and which is faster. Maybe in the second case the kernel can send the write down with the FUA bit set which would mean the difference could depend on just what file/device you were opening (because that may control whether such an optimisation can be done)...
Using O_SYNC
also makes errors appear on the return of the write()
call but as noted in other comments you're not checking the return codes...
来源:https://stackoverflow.com/questions/65828666/what-is-the-difference-between-o-direct-o-sync-write-and-o-direct-wr