【发布时间】:2016-08-10 09:59:10
【问题描述】:
我正在使用 get-content 读取一个较大的文件 (252 MB),但是当我使用 get-content 读取它时,powershell 进程继续消耗近 10 GB 的内存。这是正常行为吗?
该数组只有近 600 万个项目。它似乎与正在使用的内存量不符。
也许我只是以完全错误的方式解决这个问题。
我想将匹配字符串的行和后续行写入一个新的文本文件。
$mytext = get-content $inpath
$search = "*tacos*"
$myindex = 0..($mytext.count - 1) | Where {$mytext[$_] -like $search}
$outtext = @()
foreach ($i in $myindex){
$outtext = $outtext + $mytext[$i] + $mytext[$i+1]
}
$outtext | out-file -filepath $outpath
性能测试结果
我在这里根据不同的答案对不同的脚本进行了性能示例。
我的原始脚本
(对写出的行数高度敏感)
- 10k 行 - 1.8 秒
- 10 万行 - 38 秒
- 100k 行 - 21s(搜索字符串很少出现时)
- 5000k 行 - 太长无法测量(数小时后中止)
不带 Get-Content 的 Select-String(改编自 whatever)
Select-String -path $inpath -pattern $search -Context 0,1 -SimpleMatch | Out-File $outpath
- 10k 行 - 1.2s
- 100k 行 - 4s
- 1000k 行 - 107s
如果输入增加 10 倍,注意处理速度只会增加约 4 倍。您尝试一次处理的数据越多,该解决方案相对于其他解决方案就越好。
消除数组大小调整(来自 Mathias)
- 10k 行 - 2.0s
- 10 万行 - 25 秒
- 1000k 行 - 1533s(使用 1.7GB 内存,与在 1000k 行上在脚本之外运行 gc 相同)
使用管道(来自 Chris Dent)
- 10 万行 - 26 秒
【问题讨论】:
-
在您的示例中没有一个
Get-Content实例?
标签: powershell