我有一個 Powershell 腳本,它讀取一個 4000 KB 的文本檔案(大約 88,500 行) 這是我第一次讓我的代碼做這么多的作業。下面的腳本運行時間超過 2 分鐘,消耗了大約 20% 的 CPU(請參閱下面的任務管理器螢屏截圖)
我可以使用不同的代碼選擇來提高性能嗎?
# extractUniqueBaseNames.ps1 --- copy first UPPERCASE word in each line of text, remove duplicates & store
$listing = 'C:\roll-conversion dump\LINZ Place Street Index\StreetIndexOutput.txt'
[array]$tempStorage = $null
[array]$Storage = $null
# select only CAPITALISED first string (at least two chars or longer) from listings
Select-String -Pattern '(\b[A-Z]{2,}\b[$\s])' -Path $listing -CaseSensitive |
ForEach-Object {$newStringValue = $_.Matches.Value -replace '$\s', '\n'
$tempStorage = $newStringValue
}
$Storage = $tempStorage | Select-Object -Unique
我還添加了以下行以將結果輸出到新的文本檔案(之前的任務管理器閱讀中不包括此內容):
$Storage | Out-File -Append atest.txt
由于我處于開發的早期階段,我將不勝感激任何可以提高這種 Powershell 腳本性能的建議。
uj5u.com熱心網友回復:
如果我正確理解您的代碼,這應該會做同樣的事情,但速度更快,效率更高。
參考檔案:
StreamReader班級StreamWriter班級Regex班級File.Open方法
using namespace System.IO
using namespace System.Collections.Generic
try {
$re = [regex] '(\b[A-Z]{2,}\b[$\s])'
$reader = [StreamReader] 'some\path\to\inputfile.txt'
$stream = [File]::Open('some\path\to\outputfile.txt', [FileMode]::Append, [FileAccess]::Write)
$writer = [StreamWriter]::new($stream)
$storage = [HashSet[string]]::new()
while(-not $reader.EndOfStream) {
# if the line matches the regex
if($match = $re.Match($reader.ReadLine())) {
$line = $match.Value -replace '$\s', '\n'
# if the line hasn't been found before
if($storage.Add($line)) {
$writer.WriteLine($line)
}
}
}
}
finally {
($reader, $writer, $stream).ForEach('Dispose')
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/497576.html
