並行for循環將加速從大型文本文件讀取。鑑於您每24小時每隔10秒獲得一個1GB文件,因此實施Parallel.For循環是值得的。
大衛LOZINSKI上閱讀文本文件跑many tests(1),然後比較parallelism to regular for loops(所有的例子都採取或從大衛LOZINSKI調整。)。
對於行長度等於5個GUID(160個字符)的文本文件,使用ReadAllLines
將文本添加到數組的速度更快。
例如:
AllLines = new string[MAX]; //only allocate memory here
AllLines = File.ReadAllLines(fileName);
對於具有更長的線的文本文件(> 10組的GUID或320個字符)這是略微更快地使用ReadLine
和具有或不具有BufferedStream
創建陣列。
AllLines = new string[MAX]; //only allocate memory here
using (StreamReader sr = File.OpenText(fileName))
{
int x = 0;
while (!sr.EndOfStream)
{
AllLines[x] = sr.ReadLine();
x += 1;
}
} // The using will dispose of any resources.
然後在並行For循環內處理該數組。
Parallel.For(0, AllLines.Length, x =>
{
YourFile Processing(AllLines[x]);
});
這應該可以處理顯著更快的時間,雖然這也將取決於運行該程序的機器上,它的CPU和多少個線程可用來傳播的並行處理。
(1)感謝jason.kaisersmith在the comments
除非你正在做一些CPU密集型的數據這個環節,我沒有看到多少點。讀取文件的瓶頸不是CPU,而是硬盤。 – Rotem
我也建議看看這個:http://cc.davelozinski。com/c-sharp /最快的方式閱讀文本文件 –
我同意@Rotem,說,創新是真棒,試試看,並讓我們知道它是如何工作的。 – Trey