gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:29:20 24 4
gpt4 key购买 nike

我正在尝试实现 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.0WSManStackVersion              3.0SerializationVersion           1.1.0.1CLRVersion                     4.0.30319.18051BuildVersion                   6.2.9200.16628PSCompatibleVersions           {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 来运行脚本块。

试试这个:

measure-command { start-job -ScriptBlock {} }

这就是您创建工作所需的时间。如果您使用该作业执行的任务花费的时间少于此时间,您最好只在本地 session 中按顺序运行这些任务。

关于PowerShell 并行与顺序作业 - 顺序更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19755474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com