Skip to content

Instantly share code, notes, and snippets.

@qbikez
Created March 3, 2017 04:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qbikez/f59aa687035f879f70729d3d5dc311ad to your computer and use it in GitHub Desktop.
Save qbikez/f59aa687035f879f70729d3d5dc311ad to your computer and use it in GitHub Desktop.
a little Powershell Cmdle that makes performance measuring easier.
$script:perfstack = @()
$fullperfnames = $false
function measure-function([string] $__name, [scriptblock] $__command) {
$__result = $null
$__cmd = {
$__result = Invoke-Command $__command
}
if ($script:perfstack -eq $null) {
$script:perfstack = @()
}
$__isrecursion = $__name -in $script:perfstack
$script:perfstack += "$__name"
try {
$__r = Measure-Command $__cmd
if ($global:perfcounters -eq $null) {
$global:perfcounters = @{}
}
if ($fullperfnames) {
$__key = [string]::Join(">",$script:perfstack)
} else {
$__key = $__name
}
if ($global:perfcounters.ContainsKey($__key)) {
if (!$__isrecursion) {
$global:perfcounters[$__key].elapsed += $__r
}
$global:perfcounters[$__key].count++
} else {
$__props = [ordered]@{ name = "$__key"; elapsed = $__r; count = 1 }
$global:perfcounters[$__key] = new-object -type "pscustomobject" -property $__props
}
if ($__result -ne $null) {
return $__result
}
} finally {
$script:perfstack = $script:perfstack | select -First ($script:perfstack.Length - 1)
}
}
<#
# Usage:
# When you want to measure your functon "Get-Something"
function Get-Something {
# i'm doing some heavy loading here
return $something
}
# Add Measure-Function like this:
function Get-Something {
Measure-function "$($MyInvocation.MyCommand.Name)" {
# i'm doing some heavy loading here
return $something
}
}
# then check results in $global:perfcounters hashtable
$global:perfcounters | format-table -AutoSize -Wrap | out-string | write-host
#>
@kib
Copy link

kib commented Dec 31, 2018

I really liked your function and was using it to improve the performance of my scripts.
However, when using .NET HashSet objects, they are being converted to arrays when this wrapper is around the function.

I solved this by modifying the return like this (which works for all types of System.Collections.Generic.Hashset

            if ($__result.GetType().Name -like 'HashSet*') {
                # prevent expanding hashset causing it to become an array
                return ,$__result
            } else {
                return $__result
            }

@kib
Copy link

kib commented Dec 31, 2018

Also, to check the results in powershell > 4.0 you simply do
$Global:perfcounters.Values | ft -Autosize

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment