Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ninmonkey/4f2972c2091c66c55f44d2521eba56bc to your computer and use it in GitHub Desktop.
Save ninmonkey/4f2972c2091c66c55f44d2521eba56bc to your computer and use it in GitHub Desktop.
Compare Pwsh 7.1 vs 7.0 -Paralell (Reusable Runspaces).ps1
##Requires -Module BenchPress
Write-Host -fore Yellow 'Example of 7.1''s re-using runspace performance boost'
@'
Future:
Try -ThrottleLimit
Foreach-Object in 'Pwsh'
- 7.0
- new parameters '-Paralell', '-AsJob', '-ThrottleLimit'
- **every** iteration creates a **new** runspace (ie: slower)
- 7.1
- Runspaces from a runspace pool are reused by default (ie: faster)
- New parameter: '-UseNewRunspace'
- To force creating new runspaces like the old behaviour: -UseNewRunspace
- Pool size default is 5, set using '-ThrottleLimit'
More info:
(https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/foreach-object?view=powershell-7.2#example-14--using-thread-safe-variable-references)
(https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_thread_jobs?view=powershell-7.2)
(https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_jobs?view=powershell-7.2)
'@
$iters = 1000
$iters = 100
Write-Host -for Yellow "Items (Per test) $iters"
Measure-Benchmark -RepeatCount 3 -Detailed -Technique @{
'New Runspace' = {
# <= 7.0 behaviour
0..$iters | ForEach-Object -UseNewRunspace -Parallel {
"Hello $_ "
}
}
'Reuse Runspace' = {
# re-using runspaces in 7.1
# for the old behaviour, use -UseNewRunspace
0..$iters | ForEach-Object -Parallel {
"Hello $_ "
}
}
'-Parallel -AsJob' = {
$Jobs = 0..$iters | ForEach-Object -AsJob -Parallel {
"Hello $_"
}
$Jobs | Receive-Job -Wait
}
'-Parallel -AsJob -UseNewRunspace' = {
$Jobs = 0..$iters | ForEach-Object -UseNewRunspace -AsJob -Parallel {
"Hello $_"
}
$Jobs | Receive-Job -Wait
}
} -GroupName 'Foreach-Object -Parallel' -ov 'BenchResults'
$Summary = $BenchResults | Select-Object -p @(
'Technique'
@{name = 'Total Ms'; expression = { $_.Time.TotalMilliseconds } }
@{name = 'Average Ms'; expression = { $_.Details.AverageTime.TotalMilliseconds } }
) | Sort-Object -Property 'Average Ms'
$Summary | Format-Table
Technique Time RelativeSpeed Throughput
--------- ---- ------------- ----------
-Parallel -AsJob 00:00:02.107375 1x 1.42/s
Reuse Runspace 00:00:02.581509 1.22x 1.16/s
New Runspace 00:00:04.152241 1.97x 0.72/s
-Parallel -AsJob -UseNewRunspace 00:00:04.207801 2x 0.71/s
Technique Total Ms Average Ms
--------- -------- ----------
-Parallel -AsJob 2107.3756 702.4585
Reuse Runspace 2581.5093 860.5031
New Runspace 4152.2411 1384.0803
-Parallel -AsJob -UseNewRunspace 4207.8018 1402.6006
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment