在以下条件下,在"w“模式下打开fopen和fclose比在"a”模式下打开所花费的时间是否更长? 1.在以下logFile = fopen(log,“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分析显示在开放系统调用中需要更多的时间。这背后有什么原因吗?
下面是两个简介
76.17 0.522555 10 50006开门
12.13 0.083197 2 50006收盘
4.61 0.031626 1 50000写
3.96 0.027151 1 50002电子地图
1.57 0.010737 0 50017 mmap
1.55 0.010663 0 50007 fstat
100.00 0.686068 300060 1共计
1. **strace on code with "a" mode**- -c ./test.out -o报告
%时间秒--使用/调用错误syscall
22.08 0.020467 0 50002市政地图
20.24 0.018763 0 50000写
16.76 0.015542 0 100007 fstat
13.43 0.012450 0 50006开盘
9.90 0.009177 0 50006收盘
9.44 0.008756 0 50017 mmap
8.15 0.007558 0 50001
100.00 0.092713 400060 1共计
发布于 2015-01-14 20:23:41
对于mode="w",文件在写入之前被清空,因此系统必须:
使用mode="a",系统只具有:
显然,mode="w“做更多的工作需要更多的时间.
https://stackoverflow.com/questions/27951614
复制相似问题