functions/perfcounters.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
$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)
    }
}

<#
measure-function "test" {
    measure-function "test1" {
        write-host "hello"
    }
 }

$global:perfcounters | format-table -AutoSize -Wrap | out-string | write-host
      #>