2013-02-22 77 views
0

的巨大的名單,我從文件中
選擇從文件

// 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 > 

如上面的代碼所示。
請諮詢。

+0

你需要運行它同步,如果沒有,使用異步 – 2013-02-22 17:02:34

+0

@CuongLe手段? – Pratik 2013-02-22 17:03:17

+0

你可以在不同的線程下運行這段代碼 – 2013-02-22 17:03:53

回答

1

一些嘗試:

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次,每次。

0

如果您只需要知道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。特別是如果它的大目錄。

當我不得不在一個目錄中處理大量文件時,我繼續使用Win 32 API的FindFirstFile/FindNextFileFindClose。它提供的開銷少得多,而且速度更快。

FindFirstFile Implementation