我正在尝试实现 Windows EventLogs 的多线程解析,并且在双核系统上我发现顺序代码比并行代码快得多。这些是示例:
顺序:
$start = Get-Date
$code1 = { Get-WinEvent -Path "D:\logs\hostname-security-20131003005914.evtx" -MaxEvents 200 }
$code2 = { Get-WinEvent -Path "D:\logs\hostname-security-20131003015906.evtx" -MaxEvents 200 }
$result1 = & $code1
$result2 = & $code2
$end = Get-Date
$timespan = $end - $start
$seconds = $timespan.TotalSeconds
Write-Host "This took me $seconds seconds in all."
并行:
$start = Get-Date
$code1 = { Get-WinEvent -Path "D:\logs\hostname-security-20131003005914.evtx" -MaxEvents 200 }
$code2 = { Get-WinEvent -Path "D:\logs\hostname-security-20131003015906.evtx" -MaxEvents 200 }
$job1 = Start-Job -ScriptBlock $code1
$job2 = Start-Job -ScriptBlock $code2
$alljobs = Wait-Job $job1, $job2
$result1, $result2 = Receive-Job $alljobs
$end = Get-Date
$timespan = $end - $start
$seconds = $timespan.TotalSeconds
Write-Host "This took me $seconds seconds in all."
顺序代码运行时间约为 5 秒(CPU 使用率接近 50%),而并行代码运行时间约为 19 秒(CPU 使用率接近 100%)。我已经回显了结果,以确保它们都是正确的并且看起来不错。
我运行的是 Windows 8。PowerShell 详细信息为:
Name Value ---- ----- PSVersion 3.0 WSManStackVersion 3.0 SerializationVersion 1.1.0.1 CLRVersion 4.0.30319.18051 BuildVersion 6.2.9200.16628 PSCompatibleVersions {1.0, 2.0, 3.0} PSRemotingProtocolVersion 2.2
Any ideas?
EDIT: It is not just Get-WinEvent that produces this conundrum; I tried with Get-ChildItem with the same results.
With this as the code to execute however, the parallel code runs quicker (as expected):
$code1 = { Start-Sleep -Seconds 5; "A" }
$code2 = { Start-Sleep -Seconds 12; "B" }
连续时间为 17.002 秒。 并行 14.2 秒。
最佳答案
当您使用 Powershell 作业时,Powershell 会创建一个新 session 来运行脚本 block 。
试试这个:
measure-command { start-job -ScriptBlock {} }
这就是您创建工作所花费的时间。如果您使用该作业执行的任务花费的时间少于此时间,那么您最好在本地 session 中按顺序运行这些任务。
关于PowerShell 并行作业与顺序作业 - 顺序更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19755474/