PowerShell 并行作业与顺序作业 - 顺序更快?

标签 powershell

我正在尝试实现 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/

相关文章:

c# - PowerShell Stop-Job/Stop Job() 需要 2 分钟才能停止作业

windows - 如何在传递给 Powershell 中的函数时在参数中添加引号

Powershell 忽略错误

powershell - 使用 powershell 和 7zip 创建存档的脚本

azure - Powershell - Get-AzureADAuditSignInLogs 多个筛选器

c# - 从 C# 运行 Powershell 脚本时出错

powershell - 使用Powershell将accdb转换为csv

powershell - 如何在 Powershell 中为命令 "ls -lrt"设置别名

powershell - IF 语句中的动态条件参数?

azure - 获取 Azure Runbook 中引用函数的源代码