文章移至:http://www.cnso.org/2017/11/17/65.html
今天打算读取文件对文件内容进行操作,因为是使用MFC操作,首选CStdioFile,但是看网上说这个效率没有FILE方式高,但不确定能高多少(以前也用过,但是没有比较过),今天写了点代码,比较了一下两者的效率,结果可以看截图
文件大小:375,810,354字节
行数:84946行
测试代码如下:
void ReadFile(LPCTSTR lpszFilePath)
{
if (!PathFileExists(lpszFilePath))
{
return ;
}
__int64 nRows = 0,nRows1 = 0;
FILE *fp;
int nLen = 1024*128;
char app1[1024*128] = {0};
m_timeCount.Begin();
if(fp=_tfopen(lpszFilePath,_T("r")))
{
while(!feof(fp))
{
memset(app1,0x00,nLen);
fgets(app1,nLen,fp);
nRows ++;
}
}
fclose(fp);
__int64 nSpan = m_timeCount.End();
CStdioFile file;
CString strContent;
m_timeCount.Begin();
if (file.Open(lpszFilePath, CFile::modeRead))
{
while(file.ReadString(strContent))
{
nRows1 ++;
}
file.Close();
}
__int64 nSpan1 = m_timeCount.End();
CString str;
str.Format(_T("File:%I64d(ms)-%I64d(rows)\r\nCStdioFile:%I64d(ms)-%I64d(rows)"),nSpan,nRows,nSpan1,nRows1);
AfxMessageBox(str);
}
结果截图:
使用FILE方式读取只用了1625毫秒,CStdioFile读取耗时20714毫秒,差别太大了吧,将近二十倍,看来对于程序的效率来讲,选择合适的API很重要很重要!