Skip to main content

PowerShell function that measures the average time of a command, accounting for natural variability by automatically ignoring the top and bottom ten percent.

function Measure-CommandPerformance
{
    ##############################################################################
    ##
    ## 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 3

    ## 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
}