Zhongzhi
Zhongzhi

Reputation: 436

fwrite() is faster if unlink() the file in prior than truncate it

I want to run a simple test of disk performance on a rhel 6 platform. It's just to write down 1G bytes to the disk. I found if the file was unlinked first, it would be much faster than it was truncated. It was about 1.5s versus 15s.

Why? I thought unlink() the last hard link will truncate the file to 0 and delete the inode. Why fwrites were faster with unlink() than truncate?

#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;
}

Upvotes: 6

Views: 542

Answers (1)

Alexey Frunze
Alexey Frunze

Reputation: 62106

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

Upvotes: 5

Related Questions