Like dwks said, try writing more than 1 character at a time (indeed, you should try writing BUFSIZE characters at a time, which is a constant defined in stdio.h). You will at least save from the overhead of numerous functions calls. Also, you should use the fputs function (if you want to stay with text mode). This will speed up the whole thing.
BUFSIZ, actually; no E.
Empirical evidence:
Code:
$ time ./write1
real 0m0.054s
user 0m0.048s
sys 0m0.008s
$ time ./writeX
real 0m0.012s
user 0m0.000s
sys 0m0.012s
$ time ./write1
real 0m0.049s
user 0m0.036s
sys 0m0.012s
$ time ./writeX
real 0m0.019s
user 0m0.000s
sys 0m0.016s
$ time ./write1
real 0m0.068s
user 0m0.040s
sys 0m0.012s
$ time ./writeX
real 0m0.012s
user 0m0.000s
sys 0m0.012s
$ cat write1.c
#include <stdio.h>
int main() {
FILE *fp = fopen("write1.txt", "w");
int x;
for(x = 0; x < 1000000; x ++) {
putc(0, fp);
}
fclose(fp);
return 0;
}
$ cat writeX.c
#include <stdio.h>
int main() {
FILE *fp = fopen("writeX.txt", "w");
char buffer[BUFSIZ] = {0};
int x;
for(x = 0; x < 1000000 / BUFSIZ; x ++) {
fwrite(buffer, sizeof buffer, 1, fp);
}
fclose(fp);
return 0;
}
$
Actually, all that shows is that the binary function fwrite() is faster than the text function putc(). Though, since this is a Linux system, it shouldn't matter.