Last active
March 10, 2016 03:43
-
-
Save trammell/001262680a5b7857a021 to your computer and use it in GitHub Desktop.
Some PowerShell code benchmarking the ForEach command
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Get-Command -CommandType All | foreach { $_ } | |
foreach ($ent in Dir c:\) { $ent.Name } | |
Dir c:\ | foreach { $_.Name } | |
Dir c:\ | ForEach-Object { $_.Name } | |
function Benchmark-Command ([ScriptBlock]$Expression, [int]$Samples = 1, [Switch]$Silent, [Switch]$Long) { | |
<# | |
.SYNOPSIS | |
Runs the given script block and returns the execution duration. | |
Hat tip to StackOverflow. http://stackoverflow.com/questions/3513650/timing-a-commands-execution-in-powershell | |
.EXAMPLE | |
Benchmark-Command { ping -n 1 google.com } | |
#> | |
$timings = @() | |
do { | |
$sw = New-Object Diagnostics.Stopwatch | |
if ($Silent) { | |
$sw.Start() | |
$null = & $Expression | |
$sw.Stop() | |
Write-Host "." -NoNewLine | |
} | |
else { | |
$sw.Start() | |
& $Expression | |
$sw.Stop() | |
} | |
$timings += $sw.Elapsed | |
$Samples-- | |
} | |
while ($Samples -gt 0) | |
Write-Host | |
$stats = $timings | Measure-Object -Average -Minimum -Maximum -Property Ticks | |
# Print the full timespan if the $Long switch was given. | |
if ($Long) { | |
Write-Host "Avg: $((New-Object System.TimeSpan $stats.Average).ToString())" | |
Write-Host "Min: $((New-Object System.TimeSpan $stats.Minimum).ToString())" | |
Write-Host "Max: $((New-Object System.TimeSpan $stats.Maximum).ToString())" | |
} | |
else { | |
# Otherwise just print the milliseconds which is easier to read. | |
Write-Host "Avg: $((New-Object System.TimeSpan $stats.Average).TotalMilliseconds)ms" | |
Write-Host "Min: $((New-Object System.TimeSpan $stats.Minimum).TotalMilliseconds)ms" | |
Write-Host "Max: $((New-Object System.TimeSpan $stats.Maximum).TotalMilliseconds)ms" | |
} | |
} | |
Benchmark-Command { foreach ($ent in Dir c:\) { $ent.Name } } -Samples 1000 -Silent | |
Benchmark-Command { Dir c:\ | foreach { $_.Name } } -Samples 1000 -Silent | |
Benchmark-Command { Dir c:\ | foreach-object { $_.Name } } -Samples 1000 -Silent | |
#Benchmark-Command { foreach ($ent in Dir c:\) { $ent.Name } } -Samples 1000 -Silent | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment