【发布时间】:2010-05-14 05:33:54
【问题描述】:
我需要处理文件列表。不应对同一文件重复处理操作。我为此使用的代码是 -
using namespace std;
vector<File*> gInputFileList; //Can contain duplicates, File has member sFilename
map<string, File*> gProcessedFileList; //Using map to avoid linear search costs
void processFile(File* pFile)
{
File* pProcessedFile = gProcessedFileList[pFile->sFilename];
if(pProcessedFile != NULL)
return; //Already processed
foo(pFile); //foo() is the action to do for each file
gProcessedFileList[pFile->sFilename] = pFile;
}
void main()
{
size_t n= gInputFileList.size(); //Using array syntax (iterator syntax also gives identical performance)
for(size_t i=0; i<n; i++){
processFile(gInputFileList[i]);
}
}
代码可以正常工作,但是...
我的问题是,当输入大小为 1000 时,需要 30 分钟 - 半小时 - 在 Windows/Visual Studio 2008 Express 上。同样的输入,在Linux/gcc上运行只需40秒!
可能是什么问题?单独使用时,操作 foo() 只需很短的时间即可执行。我应该为地图使用 vector::reserve 之类的东西吗?
编辑,额外信息
foo() 的作用是: 1.它打开文件 2.读入内存 3.关闭文件 4.解析内存中文件的内容 5. 建立一个代币列表;我为此使用了一个向量。
每当我中断程序时(在运行程序时输入集超过 1000 个文件):调用堆栈显示程序处于 std::vector 添加的中间。
【问题讨论】:
-
我怀疑问题不在于 std::map,而在于 File * 类。您是否尝试过定位性能下降的阈值? Windows 和 linux 对打开文件的数量有不同的限制。
-
如果注释掉
foo(),需要多长时间? -
要获取更多信息,请删除 foo 调用。这可能是 Linux/Windows 中 STL、编译器或文件处理方面的差异。
-
问题肯定不在地图性能上!
-
上例中没有std::vector add。
标签: c++ performance stl