File append 100 times faster than modify

From: Matti Katila
Date: Thu Sep 27 2012 - 20:53:41 EST


Dear kernel people,


I would like to know why file appending is much more faster than
modifying file by other methods.
First let's just see how fast append is on my 3.2.0-18-generic-pae
#29-Ubuntu SMP

$ time for i in {1..1000}; do echo "asdf jkl" >> test ; done

real 0m0.039s
user 0m0.024s
sys 0m0.016s

That was pretty fast for old laptop.

Then insert a line. I think sed "in place" does temp file and then
move it over the original file.

$ time for i in {1..1000}; do sed -i "1iasdf jkl" test ; done

real 0m9.875s
user 0m1.300s
sys 0m6.372s

Quite slow compared to append. If we continue with append it doesn't
slow down even file size increases.

$ time for i in {1..1000}; do echo "asdf jkl" >> test ; done

real 0m0.037s
user 0m0.028s
sys 0m0.008s

Even creating new file is quite slow compared to that

$ time for i in {1..1000}; do echo "asdf jkl" > test ; done

real 0m0.719s
user 0m0.052s
sys 0m0.200s

Then let's try modifying the file in place without changing size of
the file. Here is a short command.

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char **argv)
{
char *file = argv[1];
char *chunk = argv[2];
int fd = open(file, O_WRONLY);
write(fd, chunk, strlen(chunk));
close(fd);
return 0;
}

$ gcc -o simplewrite simplewrite.c
$ time for i in {1..1000}; do ./simplewrite test $i ; done

real 0m3.666s
user 0m0.308s
sys 0m1.352s

It's still very slow compared to appending. Why are other writes so
slow and are there any tricks that could make it faster? Please cc me
if you answer.


-Matti
--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/