在以下情况下,以“w”模式打开时,fopen 和 fclose 是否比“a”模式需要更多时间 1.文件已经存在 2.没有文件存在 以下内容 日志文件 = fopen(日志,"a"); 和 logFile = fopen(log,"w");
我有以下代码,我对其进行了快速 strace 分析,以获取每个系统调用的时钟周期,并且在测试开始时不存在任何文件。
代码
int main(int argc, char **argv)
{
const char* log = "log.txt";
FILE* logFile = NULL;
char timeBuf[100];
time_t now;
struct tm *logtime1;
time(&now);
logtime1 = localtime(&now);
strftime(timeBuf,sizeof(timeBuf),"[%Y-%m-%d %H:%M:%S]",logtime1);
int i;
char *inMessage = "The Quick Brown Fox Jumps Over The Lazy Dog";
for(i=0;i<50000;i++)
{
logFile = fopen(log,"a"); //or **logFile = fopen(log,"w");**
if(logFile != NULL)
{
fflush( 0 );
int error = 0;
fprintf(logFile, "%s\t%s %d at (%s:%d)\n",timeBuf,
inMessage, error,__FILE__, __LINE__);
fclose(logFile);
}
}
return 0;
当我在“w”模式下打开文件时,strace 分析显示它在打开系统调用中花费了更多时间。这背后有什么原因吗?
下面是两个配置文件
------------ 使用“w”模式跟踪代码
strace -c ./test.out -o 报告
% time seconds usecs/call 调用错误 syscal
76.17 0.522555 10 50006 打开
12.13 0.083197 2 50006 关闭
4.61 0.031626 1 50000 写入
3.96 0.027151 1 50002 map
1.57 0.010737 0 50017mmap
1.55 0.010663 0 50007 统计
100.00 0.686068 300060 共 1
- 使用“a”模式跟踪代码
------------ strace -c ./test.out -o 报告
% time seconds usecs/call calls errors syscall
22.08 0.020467 0 50002 map
20.24 0.018763 0 50000 写入
16.76 0.015542 0 100007 统计
13.43 0.012450 0 50006 打开
9.90 0.009177 0 50006 关闭
9.44 0.008756 0 50017mmap
8.15 0.007558 0 50001 lseek
100.00 0.092713 400060 共 1
最佳答案
使用 mode="w",文件在写入前清空,因此系统必须:
- 将文件大小重置为零(打开)
- 将磁盘上使用的 block 标记为未使用(打开)
- 分配一个新 block (写入)
- 更新文件大小(写入)
使用 mode="a",系统只有:
- 分配一个新 block (有时,不总是,如果你写的东西进入一个新 block )
- 更新文件大小(写入)
显然,mode="w"做更多的工作会花费更多的时间......
关于c++ - fopen 在 "w"模式下比在 "a"模式下花费更多时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27951614/