# encoding: ascii
# api: powershell
# title: Measure-CommandPerforman
# description: From Windows PowerShell Cookbook (O’Reilly) by Lee Holmes
# version: 0.1
# type: script
# author: Lee Holmes
# license: CC0
# x-poshcode-id: 2195
# x-archived: 2016-03-18T21:11:12
# x-published: 2011-09-09T21:41:00
#
#
##############################################################################
##
## Measure-CommandPerformance
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################
<#
.SYNOPSIS
Measures the average time of a command, accounting for natural variability by
automatically ignoring the top and bottom ten percent.
.EXAMPLE
PS >Measure-CommandPerformance.ps1 { Start-Sleep -m 300 }
Count : 30
Average : 312.10155
(...)
#>
param(
## The command to measure
[Scriptblock] $Scriptblock,
## The number of times to measure the command's performance
[int] $Iterations = 30
)
Set-StrictMode -Version Latest
## Figure out how many extra iterations we need to account for the outliers
$buffer = [int] ($iterations * 0.1)
$totalIterations = $iterations + (2 * $buffer)
## Get the results
$results = 1..$totalIterations |
Foreach-Object { Measure-Command $scriptblock }
## Sort the results, and skip the outliers
$middleResults = $results | Sort TotalMilliseconds |
Select -Skip $buffer -First $iterations
## Show the average
$middleResults | Measure-Object -Average TotalMilliseconds