C 为什么写入现有文件比写入不存在的文件慢?
考虑以下示例代码:C 为什么写入现有文件比写入不存在的文件慢?,c,performance,io,fwrite,C,Performance,Io,Fwrite,考虑以下示例代码: /* verify.c */ #include <stdio.h> int main (int argc, char *argv[]) { if (argc < 2) return 0; char *filename = argv[1]; FILE *f = fopen(filename, "w"); if (!f) perror("something went wrong"); // random data
/* verify.c */
#include <stdio.h>
int
main (int argc, char *argv[])
{
if (argc < 2)
return 0;
char *filename = argv[1];
FILE *f = fopen(filename, "w");
if (!f)
perror("something went wrong");
// random data
#define SIZE 65536
#define ITER 1024
unsigned int buffer[SIZE] = { 0 };
unsigned int i;
for (i = 0; i < ITER; ++i)
{
int res = fwrite(buffer, sizeof(*buffer), SIZE, f);
if (res != SIZE)
perror("something went wrong");
}
fclose(f);
return 0;
}
为什么呢
编辑:
多亏了@rodrigo下面的建议,我通过strace
运行了这两个案例,它报告说如果文件存在,close
系统调用需要很长时间才能完成
如果文件存在:
close(3) = 0 <2.673454>
close(3)=0
否则:
close(3) = 0 <0.000011>
close(3)=0
当文件确实存在时,“w”
将截断它,即删除其所有内容。这需要时间,可能很多时间是文件非常大,文件系统不是很好(FAT?)
与此相反,当文件不存在时,将创建它,即添加目录条目和inode或文件系统使用的任何内容。但是这些结构总是很小,所以没什么大不了的。它是ext4。我希望一个文件的截断是O(1),例如,
echo”“>file
如果文件存在的话不会花费几秒钟。另外,touch file&&/verify file
也会花费大约3.8秒。@AndreasGrapentin。真奇怪。。。如果使用linux,可以运行strace-T./verifyexists
并告诉发生了什么?strace显示,当文件存在时,大量时间都花在关闭
上。写入系统调用以大约相同的速度返回。close(3)=0
vs.close(3)=0
在我的系统上没有差异(OS X 10.9.5,SSD上的HFS+)。可能,正如@rodrigo所建议的,您使用的文件系统截断文件的速度非常慢。您说echo”“>文件
不需要3秒钟,但是rm文件
呢?@rodrigorm文件
是即时的。@AndreasGrapentin:是的,我刚刚意识到我的评论是胡说八道,并删除了它:-(@rodrigo Non Concers=)
close(3) = 0 <0.000011>