在本周初创建WPF GUI时,我偶然发现了运行空间。因此,现在我知道它的存在,我希望了解基础知识。我找到以下示例https://gist.github.com/proxb/803fee30f0df244fd850并对其进行了少许(几乎没有)修改。
$w = [system.diagnostics.stopwatch]::startNew()
$Computers = “e”,”f”,”g”,”d”,”c”
$RunspaceCollection = @()
$RunspacePool = [RunspaceFactory]::CreateRunspacePool(1,5)
$RunspacePool.Open()
$ScriptBlock = {
Param($Computer)
gci $computer":" -Recurse | out-file c:\temp\t\$computer.txt
} #/ScriptBlock
Foreach ($Computer in $Computers) {
$Powershell = [PowerShell]::Create().AddScript($ScriptBlock).AddArgument($Computer)
$Powershell.RunspacePool = $RunspacePool
[Collections.Arraylist]$RunspaceCollection += New-Object -TypeName PSObject -Property @{
Runspace = $PowerShell.BeginInvoke()
PowerShell = $PowerShell
} #/New-Object
$RunspaceCollection
} #/ForEach
$w.elapsed
Write-Host "end"
因此,这遍历了我所有的磁盘,并对它们进行了get-childitem(递归)并将输出保存到txt文件中。
但是相比之下,我几乎没有速度提高:
$w = [system.diagnostics.stopwatch]::startNew()
$Computers = “e”,”f”,”g”,”d”,”c”
Foreach ($Computer in $Computers) {
gci $computer":" -Recurse | out-file c:\temp\t\$computer.txt
}
$w.elapsed
Write-Host "end"
有人可以解释为什么这样做不快吗?
我可以看到,我在启动脚本后就立即创建了所有txt文件,因此运行空间可以正常工作。
我本以为它会给我比以前更多的时间收获。自动取款机最多只能获得1-3秒的时间,甚至比“旧方法”慢一倍。
最佳答案
因此,看起来用户4c74356b41是正确的。
我早些时候进行了相同的思考过程,并为其添加了3的for循环,但似乎这还不够。如果我添加100的for循环,性能上的差异将变得更加清晰。
$w = [system.diagnostics.stopwatch]::startNew()
$Computers = “e”,”f”,”d”,”c”
$RunspaceCollection = @()
$RunspacePool = [RunspaceFactory]::CreateRunspacePool(1,5)
$RunspacePool.Open()
$ScriptBlock = {
Param($Computer)
$f = get-date -format "ddmmyyyyfff"
gci $computer":" -Recurse | out-file c:\temp\t\$computer$f.txt
} #/ScriptBlock
for($i = 0; $i -le 100; $i++){
$i
Foreach ($Computer in $Computers) {
$Powershell = [PowerShell]::Create().AddScript($ScriptBlock).AddArgument($Computer)
$Powershell.RunspacePool = $RunspacePool
[Collections.Arraylist]$RunspaceCollection += New-Object -TypeName PSObject -Property @{
Runspace = $PowerShell.BeginInvoke()
PowerShell = $PowerShell
} #/New-Object
} #/ForEach
}
While($RunspaceCollection) {
# Just a simple ForEach loop for each Runspace to get resolved
Foreach ($Runspace in $RunspaceCollection.ToArray()) {
# Here's where we actually check if the Runspace has completed
If ($Runspace.Runspace.IsCompleted) {
# Here's where we cleanup our Runspace
$Runspace.PowerShell.Dispose()
$RunspaceCollection.Remove($Runspace)
} #/If
} #/ForEach
} #/While
$w.elapsed
Write-Host "end"
这将需要:
分钟:4
秒:23
毫秒:273
在哪里
$w = [system.diagnostics.stopwatch]::startNew()
$Computers = “e”,”f”,”d”,”c”
for($i = 0; $i -le 100; $i++){
$i
Foreach ($Computer in $Computers) {
$f = get-date -format "ddmmyyyyfff"
gci $computer":" -Recurse | out-file c:\temp\t\$computer$f.txt
$w.elapsed
}
}
$w.elapsed
Write-Host "end 100 times"
将采取
分钟:9
秒:38
毫秒:932