Created
March 26, 2012 16:48
-
-
Save jpoehls/2206444 to your computer and use it in GitHub Desktop.
PowerShell benchmarking function. Or, the Windows equivalent of Unix's `time` command.
This file contains hidden or 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
function Measure-Command2 ([ScriptBlock]$Expression, [int]$Samples = 1, [Switch]$Silent) { | |
<# | |
.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 | |
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())" | |
} | |
Set-Alias time Measure-Command2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment