Fwrite () is faster if unlink () a file in the previous one than trimming it

I want to run a simple disk performance test on the rhel 6 platform. It just writes 1 GB to the disk. I found that if the file was detached first, it would be much faster than being truncated. This was about 1.5 s versus 15 s.

Why? I thought unlink () the last hard link truncates the file to 0 and remove the inode. Why were fwrites faster with shutdown () than truncation?

#include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, char* argv[]) { if (argc < 2) { return -1; } char buf[1024]; srand(time(0)); int i; for (i = 0; i < 1024; ++i) { buf[i] = rand(); } /* unlink(argv[1]); */ FILE* fp = fopen(argv[1], "wb+"); if (fp == NULL) { perror("fopen"); return -1; } for (i = 0; i < 1024 * 1024; ++i) { if (fwrite(buf, 1024, 1, fp) != 1) { perror("fwrite"); return -1; } } return 0; } 
+6
source share
1 answer

Deleting a file may appear faster than truncating it when you have enough free disk space, and the file system can delete files and lazily free up their space. It can simply mark the inode as deleted and delete the file in the background or later and create a new inode almost instantly, ready for new entries.

+5
source

All Articles