Skip to content

Instantly share code, notes, and snippets.

@jpoehls
Created March 26, 2012 16:48
Show Gist options
  • Save jpoehls/2206444 to your computer and use it in GitHub Desktop.
Save jpoehls/2206444 to your computer and use it in GitHub Desktop.
PowerShell benchmarking function. Or, the Windows equivalent of Unix's `time` command.
PS> time { ping -n 1 google.com } -Samples 10 -Silent
..........
Avg: 62.1674ms
Min: 56.9945ms
Max: 87.9602ms
PS> time { ping -n 1 google.com } -Samples 10 -Silent -Long
..........
Avg: 00:00:00.0612480
Min: 00:00:00.0572167
Max: 00:00:00.0765762
function Measure-Command2 ([ScriptBlock]$Expression, [int]$Samples = 1, [Switch]$Silent, [Switch]$Long) {
<#
.SYNOPSIS
Runs the given script block and returns the execution duration.
Discovered on StackOverflow. http://stackoverflow.com/questions/3513650/timing-a-commands-execution-in-powershell
.EXAMPLE
Measure-Command2 { 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"
}
}
Set-Alias time Measure-Command2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment