我正在从庞大的文件列表中选择前一天的文件
// selecting around 80-120 files from 20,000 - 25,000
FileInfo[] files = (new DirectoryInfo(dirPath)).GetFiles("*.xml");
string[] selectedFiles = (from c in files
where c.CreationTime >= DateTime.Today.AddDays(-1) && c.CreationTime < DateTime.Today.AddHours(-2.0)
select c.FullName).ToArray();上面的运行大约需要4-5分钟,你能告诉我如何在不改变功能的情况下优化它吗?
// file selection is between yesterday 0:00 to yesterday 22:00 <br >如上面的代码所示。
温馨的建议。
发布于 2013-02-23 01:06:29
一些可以尝试的东西:
FileInfo[] files = (new DirectoryInfo(dirPath)).GetFiles("*.xml");
DateTime lowDate = DateTime.Today.AddDays(-1);
DateTime highDate = DateTime.Today.AddHours(-2.0);
string[] selectedFiles = (from c in files
where c.CreationTime >= lowDate && c.CreationTime < highDate
select c.FullName).ToArray();有可能这些日期都是通过20,000+时间计算出来的。
发布于 2013-02-23 02:22:13
如果您只需要知道CreationTime,那么不要为每个文件实例化一个新的FileInfo类。而且,您也不必使用DirectoryInfo。
我会使用类似这样的东西:
DateTime lowDate = DateTime.Today.AddDays(-1);
DateTime highDate = DateTime.Today.AddHours(-2.0);
var filteredFileNames = new List<String>();
string[] fileNames;
fileNames = Directory.GetFiles(dirPath, "*.xml")
for (int i = 0; i < fileNames.Length; i++)
{
var creationTime = File.GetCreationTimeUtc(fileNames[i]);
if(creationTime >= lowDate && creationTime < highDate)
{
filteredFileNames.Add(filenNames[i]);
}
}如果您不受I/O限制,您仍然可以将时间范围的一部分划分为不同的Tasks / Threads (取决于您使用的.NET版本),并在最后累积名称。然而,大部分工作都是使用Directory.GetFiles完成的。特别是如果它是一个大目录的话。
当我不得不在一个目录中处理大量文件时,我继续使用win32API的FindFirstFile/ FindNextFile和FindClose。它提供的开销要少得多,而且速度更快。
FindFirstFile Implementation
https://stackoverflow.com/questions/15029216
复制相似问题