簡體   English   中英

性能調整Powershell文本處理

[英]Performance tuning powershell text processing

我有一個用C#編寫的SSIS腳本任務,我希望將其移植到powershell用作腳本。 C#版本的運行時間為12.1s,而powershell版本的運行時間為100.5s,幾乎慢了一個數量級。 我正在處理11種文本文件(csv),每種格式約3-4百萬行:

<TICKER>,<DTYYYYMMDD>,<TIME>,<OPEN>,<HIGH>,<LOW>,<CLOSE>,<VOL>
AUDJPY,20010102,230100,64.30,64.30,64.30,64.30,4
AUDJPY,20010102,230300,64.29,64.29,64.29,64.29,4
<snip>

我只想將內容寫到一個新文件中,該列的日期為20110101或更高。 這是我的C#版本:

    private void ProcessFile(string fileName)
    {
        string outfile = fileName + ".processed";
        StringBuilder sb = new StringBuilder();
        using (StreamReader sr = new StreamReader(fileName))
        {
            string line;
            int year;
            while ((line = sr.ReadLine()) != null)
            {
                year = Convert.ToInt32( sr.ReadLine().Substring(7, 4));
                if (year >= 2011)
                {
                    sb.AppendLine(sr.ReadLine());
                }
            }
        }

        using (StreamWriter sw = new StreamWriter(outfile))
        {
            sw.Write(sb.ToString());
        }
    }

這是我的powershell版本:

foreach($file in ls $PriceFolder\*.txt) {
    $outFile = $file.FullName + ".processed"
    $sr = New-Object System.IO.StreamReader($file)
    $sw = New-Object System.IO.StreamWriter($outFile)
    while(($line = $sr.ReadLine() -ne $null))
    {       
        if ($sr.ReadLine().SubString(7,4) -eq "2011") {$sw.WriteLine($sr.ReadLine())}
    }   
}

如何在Powershell中獲得與SSIS中的C#腳本任務相同的性能?

除非您實際上在PowerShell中使用C#,否則您將無法獲得與C#相當的PowerShell性能。 Add-Type cmdlet允許編譯一些通常不重要的C#代碼片段,並直接從腳本中調用它們。 如果性能是一個問題,並且由於某些原因無法使用C#程序集,那么我會采用這種方式。

在此處查看示例: http : //go.microsoft.com/fwlink/?LinkID=135195

不久前,我看到一個問題並試圖回答它-看http://social.technet.microsoft.com/Forums/en/winserverpowershell/thread/da36e346-887f-4456-b908-5ad4ddb2daa9 坦白說,使用PowerShell時的性能損失非常大,以至於對於耗時的任務,我總是會選擇@Roman建議的C#或Add-Type

您正在將C#轉換為Powershell,這在所有情況下可能都不理想。 是的,使用C#可以提高性能,但這並不意味着您也無法通過Powershell獲得比較性能。

您應該嘗試利用Powershell管道中的“流式傳輸”。

例如,類似:

gc file.txt | ?{ process.....} | %{process...} | out-file out.txt

一旦對象可用,它們就會沿管道傳遞,因此速度會更快。

您可以使用Get-Content和流水線嘗試使用等效方法嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM