### Install Profiler and share feedback Source: https://github.com/nohwnd/profiler/blob/main/presentation-v3/Profiler.pdf Install Profiler and share feedback. ```powershell Install it: Install-Module Profiler Share feedback: github.com/nohwnd/profiler Follow me on twitter: @nohwnd ``` -------------------------------- ### Install Profiler module from PowerShell Gallery Source: https://github.com/nohwnd/profiler/blob/main/README.MD Installs the Profiler module from the PowerShell Gallery. Requires PowerShell 5 or 7 and works on Windows, Linux, and macOS. ```powershell Install-Module Profiler ``` -------------------------------- ### Comparing before/after changes with -Flag Source: https://github.com/nohwnd/profiler Uses the -Flag parameter to run each repetition twice: once with all flags false (Before) and once with the hashtable values (After). The example preheats twice and repeats three times, printing per-run comparison lines with the difference in milliseconds. ```powershell # MyScript.ps1 wraps the new implementation in: if ($_profiler) { ... } else { ... } $flag = @{ _profiler = $true } Invoke-Script -ScriptBlock { & .\MyScript.ps1 } -Preheat 2 -Repeat 3 -Flag $flag # Output (host): # Run 1: 00:00:02.100 -> 00:00:01.400 (-700 ms) # Run 2: 00:00:02.050 -> 00:00:01.350 (-700 ms) # Run 3: 00:00:02.000 -> 00:00:01.300 (-700 ms) ``` -------------------------------- ### Drill from a slow line to its raw events Source: https://github.com/nohwnd/profiler Finds a specific line in Top50Duration, gets its first hit, and shows the events inside that call sorted by self duration. ```powershell $slow = $trace.Top50Duration | Where-Object { $_.Text -eq 'c' } | Select-Object -First 1 $hit = $slow.Hits[0] # everything that happened inside the call, from its index to its return $trace.Events[$hit.Index..$hit.ReturnIndex] | Sort-Object SelfDuration -Descending | Select-Object -First 10 Text, SelfDuration, Level, Flow ``` -------------------------------- ### Basic timing with Invoke-Script Source: https://github.com/nohwnd/profiler Measures a script block with plain stopwatch timing. The example imports the Profiler module and runs Invoke-Pester three times, printing each run's duration to the host. ```powershell Import-Module Profiler Invoke-Script -ScriptBlock { Import-Module Pester; Invoke-Pester } -Repeat 3 # Output (host): # Run 1 finished after 00:00:12.340... # Run 2 finished after 00:00:11.100... # Run 3 finished after 00:00:11.050... ``` -------------------------------- ### ShouldRegisterTracer method signature Source: https://github.com/nohwnd/profiler Decides whether to Patch (install a new session) or Register (add to slot 2). Throws ArgumentNullException if tracer is null. With overwrite=true (default), returns HasDifferentTracer(Tracer1, tracer); with overwrite=false, returns whether slot 1 is occupied. No side effects. ```csharp public static bool ShouldRegisterTracer(object tracer, bool overwrite = true) ``` -------------------------------- ### Profile a script block with Trace-Script Source: https://github.com/nohwnd/profiler/blob/main/README.MD Profiles any script block, including module functions. The example imports the Pester module and runs Invoke-Pester. Note: excluding files like Pester internals from profiling is planned. ```powershell $scriptBlock = { Import-Module Pester Invoke-Pester } Trace-Script -ScriptBlock $scriptBlock ``` -------------------------------- ### Registering a custom tracer on an existing session Source: https://github.com/nohwnd/profiler Shows how to register a custom tracer on an existing session. The custom tracer must implement `ITracer` (or expose a compatible `Trace` method). The example patches the session, enables tracing, registers the custom tracer in slot 2, runs a script block, then unregisters and unpatch in a `finally` block. ```powershell Import-Module Profiler # Custom tracer object must implement ITracer (or expose a compatible Trace method). class MyTracer : Profiler.ITracer { [void] Trace([string] $message, [System.Management.Automation.Language.IScriptExtent] $extent, [System.Management.Automation.ScriptBlock] $scriptBlock, [int] $level, [string] $functionName, [string] $moduleName) { "TRACE: $functionName $($extent.Text)" | Out-Host } } $tracer = [Profiler.ProfilerTracer]::new() $tracer2 = [MyTracer]::new() $null = [Profiler.Tracer]::Patch($PSVersionTable.PSVersion.Major, $ExecutionContext, $host.UI, $tracer) $null = Set-PSDebug -Trace 1 try { $null = [Profiler.Tracer]::Register($tracer2) # slot 2; use ShouldRegisterTracer to decide & { Start-Sleep -Milliseconds 50 } } finally { $null = Set-PSDebug -Trace 0 [Profiler.Tracer]::Unregister() # removes slot 2, tracing continues in slot 1 [Profiler.Tracer]::Unpatch() } ``` -------------------------------- ### SpeedScopeProfile class Source: https://github.com/nohwnd/profiler Represents a single profile with type, name, unit, start and end values, and a list of events. Source: csharp/Profiler/SpeedScope/SpeedScopeProfile.cs. ```csharp public class SpeedScopeProfile { public string Type { get; set; } public string Name { get; set; } public string Unit { get; set; } public int StartValue { get; set; } public decimal EndValue { get; set; } public List Events { get; set; } } ``` -------------------------------- ### ShouldRegisterTracer Source: https://github.com/nohwnd/profiler Determines whether to install a new trace session via Patch or add the tracer to slot 2 via Register. Returns a boolean indicating whether the tracer should be registered. ```APIDOC ## ShouldRegisterTracer ### Description Decides whether to `Patch` (install a new session) or `Register` (add to slot 2). Returns `bool`; has no side effects. ### Method ShouldRegisterTracer ### Signature ```csharp public static bool ShouldRegisterTracer(object tracer, bool overwrite = true) ``` ### Parameters - **tracer** (object) - Required - The tracer object to evaluate. - **overwrite** (bool) - Optional - Defaults to `true`. When `true`, returns `HasDifferentTracer(Tracer1, tracer)`; when `false`, returns whether slot 1 is occupied (`HasTracer(Tracer1)`). ### Returns - **bool** - `true` if the tracer should be registered, `false` otherwise. ### Behavior - `tracer is null` → `ArgumentNullException`. - `overwrite = true` (default): returns `HasDifferentTracer(Tracer1, tracer)` — `false` when slot 1 is empty or holds a tracer of the *same type name*, `true` when it holds a different type name (in which case the caller should `Register`). - `overwrite = false`: returns whether slot 1 is occupied (`HasTracer(Tracer1)`); nested Profiler-in-Profiler runs use this so the inner tracer goes to slot 2 even for the same type. - Comparison for `ExternalTracerAdapter` instances compares the wrapped `Tracer.GetType().Name` (`adapted.Tracer.GetType().Name`). ``` -------------------------------- ### Tracer class declaration Source: https://github.com/nohwnd/profiler Static class managing trace session installation and tracer slots. Replaces the host's external UI with an interception proxy and reads the debugger's internal call stack via reflection. ```csharp public static class Tracer { public static ITracer Tracer1 { get; private set; } public static ITracer Tracer2 { get; private set; } public static bool ShouldRegisterTracer(object tracer, bool overwrite = true) public static void Register(object tracer) public static void Unregister() public static void Patch(int powerShellVersion, EngineIntrinsics context, PSHostUserInterface ui, ITracer tracer) public static void Unpatch() } ``` -------------------------------- ### Try this: profile script and module Source: https://github.com/nohwnd/profiler/blob/main/presentation-v3/Profiler.pdf Profile a script with parameters and a module. ```powershell # profile a script, even if it takes parameters $trace = Trace-Script {.\myScript.ps1-Name'Jakub'-Age 32} # profile a module $trace = Trace-Script { Import-Module.\Planets.psm1 Get-Planet-Name'M*' } ``` -------------------------------- ### The three problems Source: https://github.com/nohwnd/profiler/blob/main/presentation-v3/Profiler.pdf Lists the three key questions for performance optimization. ```text -Which code is slow? -Which code is worth optimizing? -How do I optimize it? ``` -------------------------------- ### Basic replay with Show-ScriptExecution Source: https://github.com/nohwnd/profiler Imports the Profiler module, traces a script, and replays the trace with Show-ScriptExecution. Requires the Profiler module and the demo script SleepyScript.ps1. ```powershell Import-Module Profiler $trace = Trace-Script { & .\demo-scripts\SleepyScript.ps1 } Show-ScriptExecution -Trace $trace ``` -------------------------------- ### Inspect the top report Source: https://github.com/nohwnd/profiler Loads the Profiler module, traces a script, and displays the top duration reports using Format-Table. ```powershell Import-Module Profiler $trace = Trace-Script -ScriptBlock { & .\demo-scripts\SleepyScript.ps1 } $trace.Top50Duration | Format-Table $trace.Top50SelfDuration | Format-Table $trace.Top50FunctionSelfDuration | Format-Table ``` -------------------------------- ### Which code is worth optimizing? Source: https://github.com/nohwnd/profiler/blob/main/presentation-v3/Profiler.pdf Use Percent and HitCount to find code worth optimizing. ```text -Look at Percent, and HitCount -Look for code that runs many times, or for every item you have ``` -------------------------------- ### Show-ScriptExecution Source: https://github.com/nohwnd/profiler Replays a trace on the host, printing each trace event indented by call depth with a heat color computed from its self-duration share. Optionally sleeps proportionally to simulate original execution speed. ```APIDOC ## Show-ScriptExecution ### Description Replays a trace on the host: prints each trace event indented by call depth with a heat color computed from its self-duration share, and can sleep proportionally to simulate original execution speed. ### Signature ```powershell function Show-ScriptExecution { [CmdletBinding()] param( $Trace, [switch] $x1, [switch] $x10, [switch] $x100, [switch] $x1000 # , # [switch] $Color ) ... } ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `Trace` | untyped (any object with `.Events` and `.TotalDuration`) | No | latest trace | Trace to replay; when omitted, `Get-LatestTrace` is used. | | `x1` | `switch` | No | off | Slowdown factor 1 (sleep `SelfDuration * 1`). | | `x10` | `switch` | No | off | Slowdown factor 10. | | `x100` | `switch` | No | off | Slowdown factor 100. | | `x1000` | `switch` | No | off | Slowdown factor 1000. | Slowdown factors are mutually exclusive in priority order `x1000` > `x100` > `x10` > `x1`; with no switch, `x = 0` and no sleeping occurs. ### Returns Nothing. Each event is written with `Write-Host`: ``` (, %) ``` - Text is `$e.Extent.Text.ToString().Trim()`. - Margin is `' ' * $e.Level` — deeper calls are indented further. - Color is picked from the heat palette `@(226, 220, 214, 124, 196)` (256-color ANSI) based on the event's `SelfDuration` as a percent of `Trace.TotalDuration`: `>20%` → index 4 (red), `>10%` → 3, `>5%` → 2, `>3%` → 1, `>1%` → 0, else no color. ANSI codes used: `\e[38;5;m` … `\e[0m`. - When a slowdown switch is on: `[System.Threading.Thread]::Sleep($e.SelfDuration * $x)` after each line (the source notes the built-in `<15ms` sleep resolution makes this inaccurate for fast lines). The commented-out `$blueToGreen = $false` branch shows an alternative color mode (level-based palette) that is disabled; heat mode is always active. ### Examples #### Basic replay ```powershell Import-Module Profiler $trace = Trace-Script { & .\demo-scripts\SleepyScript.ps1 } Show-ScriptExecution -Trace $trace ``` #### Reusing the latest trace at 100x slowdown ```powershell Trace-Script -ScriptBlock { & .\demo-scripts\Get-Icons.ps1 } Show-ScriptExecution -x100 ``` #### Error handling The function itself performs no error handling; using it before any `Trace-Script` run makes `Get-LatestTrace` warn and return nothing, which surfaces as a null dereference when `$trace.Events` is accessed: ```powershell try { Show-ScriptExecution # no trace yet } catch { Write-Host "Cannot show execution: $($_.Exception.Message)" # e.g. 'Cannot index into a null array' } ``` ### Related - [get-latest-trace.md](get-latest-trace.md) — default trace source. - [types.md](../types.md) — `Hit.Level`, `Hit.SelfDuration`, `Hit.Extent`. ``` -------------------------------- ### Using ProfilerTracer's raw output (as Trace-Script does) Source: https://github.com/nohwnd/profiler Creates a ProfilerTracer, patches the engine, runs a script with tracing enabled, then processes raw hits and script blocks using Profiler.ProcessFlow and Profiler.ProcessLines. ```powershell $tracer = [Profiler.ProfilerTracer]::new() $null = [Profiler.Tracer]::Patch($PSVersionTable.PSVersion.Major, $ExecutionContext, $host.UI, $tracer) $null = Set-PSDebug -Trace 1 try { & { Start-Sleep -Milliseconds 10 } } finally { $null = Set-PSDebug -Trace 0 [Profiler.Tracer]::Unpatch() } # raw events, then run the processing pipeline: $flow = [Profiler.Profiler]::ProcessFlow($tracer.Hits) $fileMap = [Profiler.Profiler]::ProcessLines($flow, $tracer.ScriptBlocks, $false) ``` -------------------------------- ### Trace-Script -ExportPath Source: https://github.com/nohwnd/profiler Traces a script block and exports the trace to a SpeedScope file in one step. The export path can be a directory or a template with placeholder. ```APIDOC ## Trace-Script -ExportPath ### Description Traces a script block and exports the trace to a SpeedScope file in one step. The export path can be a directory or a template with placeholder. ### Method PowerShell function ### Parameters - **-ScriptBlock** (scriptblock) - Required - The script block to trace. - **-ExportPath** (string) - Required - Output directory or file template. If directory, auto-generated filename; if template, is replaced with a unique run id. ### Response Writes a SpeedScope JSON file to the specified path. ### Request Example ```powershell # directory form Trace-Script -ScriptBlock { & .\demo-scripts\Get-Icons.ps1 } -ExportPath ./icons # template form — unique file per run Trace-Script -ScriptBlock { & .\demo-scripts\Get-Icons.ps1 } -ExportPath "run_.speedscope.json" ``` ``` -------------------------------- ### Memory report Source: https://github.com/nohwnd/profiler Traces a script and displays the top self memory allocations using Format-Table. ```powershell $trace = Trace-Script { & .\demo-scripts\MyScript.ps1 } $trace.Top50SelfMemory | Format-Table Text, SelfMemory, SelfMemoryPercent ``` -------------------------------- ### SpeedScope C# class signatures Source: https://github.com/nohwnd/profiler Public static class with `Export` and `Convert` methods. `Export` serializes the converted report as indented, camelCase JSON into a file and returns the full path. `Convert` builds a `SpeedScopeReport` with evented profile type, deduplicated frames, and internal Profiler events skipped. ```csharp public static class SpeedScope { public static string Export(string exporter, Trace trace, string directory, string name) public static SpeedScopeReport Convert(string exporter, Trace trace, string name) } ``` -------------------------------- ### Trace-Script -Flag Source: https://github.com/nohwnd/profiler Configures feature-flag comparison for the Trace-Script cmdlet. Maps flag names to values, with optional -Before and -After switches. ```APIDOC ## [Hashtable] -Flag ### Description Maps flag names to values for feature-flag comparison. Each key is defined as a `$global:` variable: `$false` for the "before" side and the hashtable value for the "after" side. ### Parameters #### -Flag - **Type**: `[Hashtable]` - **Required**: Yes - **Description**: Mapping of flag names to values. #### -Before - **Type**: Switch - **Required**: No - **Description**: Forces all flags to `$false`. #### -After - **Type**: Switch - **Required**: No - **Description**: Uses hashtable values; wins over `-Before`. ``` -------------------------------- ### SpeedScope.Convert(string exporter, Trace trace, string name) Source: https://github.com/nohwnd/profiler Builds a SpeedScopeReport from the given trace, converting events and frames into the SpeedScope format. Throws InvalidOperationException on a Return with an empty call stack. ```APIDOC ## SpeedScope.Convert(string exporter, Trace trace, string name) ### Description Builds a SpeedScopeReport from the given trace, converting events and frames into the SpeedScope format. Throws InvalidOperationException on a Return with an empty call stack. ### Method N/A (C# static method) ### Parameters #### Parameters - **exporter** (string) - Required - The exporter identifier, e.g., `"Profiler@4.3.0"`. - **trace** (Trace) - Required - The trace data to convert. - **name** (string) - Required - The profile name to use. ### Response #### Success Response Returns a SpeedScopeReport object. #### Error Response Throws InvalidOperationException on a Return with an empty call stack. ``` -------------------------------- ### Before/after comparison with -Flag, -Before, -After Source: https://github.com/nohwnd/profiler Uses feature flags to compare before and after runs. For -Before, all flags are $false; for -After, flags are set to hashtable values. Guard improved code with if ($_profiler) to switch behavior. ```powershell $flag = @{ _iteration = $true; _enumerable = $true } # before side (all flags $false) Trace-Script -ScriptBlock { & .\MyScript.ps1 } -Flag $flag -Before # after side (flags set to hashtable values) $trace = Trace-Script -ScriptBlock { & .\MyScript.ps1 } -Flag $flag -After $trace.Top50Duration | Format-Table ``` -------------------------------- ### Reusing latest trace at 100x slowdown Source: https://github.com/nohwnd/profiler Traces a script without storing the result, then replays the latest trace with the -x100 switch to sleep proportionally to self-duration times 100. Requires the Profiler module and the demo script Get-Icons.ps1. ```powershell Trace-Script -ScriptBlock { & .\demo-scripts\Get-Icons.ps1 } Show-ScriptExecution -x100 ``` -------------------------------- ### Basic usage with Import-Module Source: https://github.com/nohwnd/profiler Imports the module, runs Trace-Script without assignment, then retrieves the trace with Get-LatestTrace and displays Top50SelfDuration. ```powershell Import-Module Profiler Trace-Script -ScriptBlock { Start-Sleep -Milliseconds 100 } # unassigned $trace = Get-LatestTrace $trace.Top50SelfDuration | Format-Table ``` -------------------------------- ### Invoke-Script -Flag Source: https://github.com/nohwnd/profiler Configures feature-flag comparison for the Invoke-Script cmdlet. Maps flag names to values. ```APIDOC ## [Hashtable] -Flag ### Description Maps flag names to values for feature-flag comparison. Each key is defined as a `$global:` variable: `$false` for the "before" side and the hashtable value for the "after" side. ``` -------------------------------- ### Load Profiler.dll based on PowerShell version Source: https://github.com/nohwnd/profiler Selects the appropriate Profiler.dll assembly at import time based on the PowerShell major version. PowerShell 7.x loads net6.0, 5.x loads net452, and older majors load net451 (though later rejected by Assert-PowerShellVersion). ```powershell if ($PSVersionTable.PSVersion.Major -ge 7) { [Reflection.Assembly]::LoadFrom("$PSScriptRoot/bin/net6.0/Profiler.dll") } elseif ($PSVersionTable.PSVersion.Major -ge 5) { [Reflection.Assembly]::LoadFrom("$PSScriptRoot/bin/net452/Profiler.dll") } else { [Reflection.Assembly]::LoadFrom("$PSScriptRoot/bin/net451/Profiler.dll") } ``` -------------------------------- ### Manual pipeline equivalent to Trace-Script internals Source: https://github.com/nohwnd/profiler Shows the full manual pipeline: patch, trace, process flow/lines/functions, and display top 10 by self duration. ```powershell Import-Module Profiler $tracer = [Profiler.ProfilerTracer]::new() $null = [Profiler.Tracer]::Patch($PSVersionTable.PSVersion.Major, $ExecutionContext, $host.UI, $tracer) $null = Set-PSDebug -Trace 1 try { & { Start-Sleep -Milliseconds 10 } } finally { $null = Set-PSDebug -Trace 0 [Profiler.Tracer]::Unpatch() } $trace = [Profiler.Profiler]::ProcessFlow($tracer.Hits) $fileMap = [Profiler.Profiler]::ProcessLines($trace, $tracer.ScriptBlocks, $true) $functionMap = [Profiler.Profiler]::ProcessFunctions($trace) $fileMap.Values.Lines.Values | Sort-Object SelfDuration -Descending | Select-Object -First 10 Text, SelfDuration, HitCount ``` -------------------------------- ### Trace-Script for any scriptblock Source: https://github.com/nohwnd/profiler/blob/main/presentation-v3/Profiler.pdf Profile any scriptblock, as used in demos. ```powershell $trace = Trace-Script { "hello" } ``` -------------------------------- ### Trace-Script Source: https://github.com/nohwnd/profiler The main entry point for the profiler: instruments the session, executes a ScriptBlock under statement tracing, processes the raw trace into line/function statistics and returns a [Profiler.Trace]. It accepts a script block to profile, optional preheat runs, feature flags for before/after comparison, and an export path for speedscope JSON. ```APIDOC ## Trace-Script ### Description The main entry point: instruments the session, executes a ScriptBlock under statement tracing, processes the raw trace into line/function statistics and returns a `[Profiler.Trace]`. ### Method Function ### Signature ```powershell function Trace-Script { [CmdletBinding()] param( [Parameter(Mandatory)] [ScriptBlock] $ScriptBlock, # [string[]] $FilterPath, [uint32] $Preheat = 0, [Switch] $DisableWarning, [Hashtable] $Flag, [Switch] $Before, [Switch] $After, [string] $ExportPath ) ... } ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `ScriptBlock` | `System.Management.Automation.ScriptBlock` | Yes | — | The script, script file invocation (`& .\file.ps1`), or module code to profile. | | `Preheat` | `uint32` | No | `0` | Number of warm-up runs executed (through the tracer) before the measured run. Default 0. | | `DisableWarning` | `Switch` | No | off | Disables a warning about `Preheat` on PowerShell 7 (the warning itself is not implemented in this snapshot; the switch is plumbed through to `Trace-ScriptInternal`). | | `Flag` | `Hashtable` | No | `$null` | Feature-flags for before/after comparison; each key becomes a `$global:` variable. See below. | | `Before` | `Switch` | No | off | Forces all `Flag` values to `$false` (runs code "before changes"). | | `After` | `Switch` | No | off | Forces all `Flag` values to the hashtable values; wins when both `-Before` and `-After` are given (a warning is written). | | `ExportPath` | `string` | No | `$null` | Exports the trace to speedscope JSON (invokes `Export-SpeedScope`). See [export-speedscope.md](export-speedscope.md) for path semantics. | ### Returns `[Profiler.Trace]` - The processed trace with line/function statistics. ``` -------------------------------- ### Trace-Script for module load Source: https://github.com/nohwnd/profiler/blob/main/presentation-v3/Profiler.pdf Profile a module including its load time. ```powershell $trace = Trace-Script { Import-Module .\Planets.psm1 Get-Planet -Name 'M*' } ``` -------------------------------- ### Aggregating AllLines Source: https://github.com/nohwnd/profiler Builds a custom object with line count, total hits, total duration, and overhead from the trace's AllLines and duration properties. ```powershell $all = $trace.AllLines [pscustomobject]@{ Lines = $all.Count TotalHits = ($all | Measure-Object HitCount -Sum).Sum TotalMs = $trace.TotalDuration.TotalMilliseconds OverheadMs = $trace.StopwatchDuration.TotalMilliseconds - $trace.TotalDuration.TotalMilliseconds } ``` -------------------------------- ### Export via the PowerShell function Source: https://github.com/nohwnd/profiler Imports the Profiler module, traces a script, and exports the trace to a SpeedScope JSON file. The output path is a directory; the file is named profiler_0000.speedscope.json with an incrementing id per run. ```powershell Import-Module Profiler $trace = Trace-Script { & .\demo-scripts\MyScript.ps1 } Export-SpeedScope -Trace $trace -Path ./report # ./report/profiler_0000.speedscope.json (id increments per run) ``` -------------------------------- ### Trace-Script with parameters Source: https://github.com/nohwnd/profiler/blob/main/presentation-v3/Profiler.pdf Profile a script that takes parameters using Trace-Script. ```powershell $trace = Trace-Script { & .\myScript.ps1-Name 'Jakub'-Age 32 } ``` -------------------------------- ### Catch unsupported PowerShell version in consumer code Source: https://github.com/nohwnd/profiler Shows how to catch the Assert-PowerShellVersion error when calling Trace-Script. ```powershell try { $trace = Trace-Script { Start-Sleep -Milliseconds 100 } } catch { Write-Host "Profiling is unavailable: $_" } ``` -------------------------------- ### Enable precise memory measurement with POWERSHELL_PROFILER_PRECISE_MORY_MEASUREMENT Source: https://github.com/nohwnd/profiler Sets the environment variable to "1" to enable precise (slower) allocated-bytes measurement for the current session. The variable is read once when ProfilerTracer is constructed, i.e., per Trace-Script run. Any other value or unset uses imprecise measurement. ```powershell # Enable precise (slower) allocated-bytes measurement for the current session $env:POWERSHELL_PROFILER_PRECISE_MEMORY_MEASUREMENT = "1" # The variable is read when ProfilerTracer is constructed, i.e. per Trace-Script run $trace = Trace-Script { & .\MyScript.ps1 } ``` -------------------------------- ### Get-NextName (helper) Source: https://github.com/nohwnd/profiler Resolves the next available `` filename based on the provided path and name template. Throws when all ids 0000–9999 are taken. ```APIDOC ## Get-NextName (helper) ### Description Resolves the next available `` filename based on the provided path and name template. Throws when all ids 0000–9999 are taken. ### Method N/A (PowerShell function) ### Parameters #### Path Parameters - **Path** (string) - Required - The directory path where the file will be created. - **Name** (string) - Optional - The filename template with `` placeholder. Default is `profiler_.speedscope.json`. ### Response #### Success Response Returns the next available filename with the `` replaced by a number. #### Error Response Throws an error when all ids 0000–9999 are taken. ``` -------------------------------- ### Invoke-Script Source: https://github.com/nohwnd/profiler Runs a ScriptBlock with plain stopwatch timing (no statement tracing) for quick measurements and before/after comparisons. Prints results to the host; returns nothing. ```APIDOC ## Invoke-Script ### Description Runs a ScriptBlock with plain stopwatch timing (no statement tracing) for quick measurements and before/after comparisons. Prints results to the host; returns nothing. ### Signature ```powershell function Invoke-Script { param( [Parameter(Mandatory)] [ScriptBlock] $ScriptBlock, [uint32] $Repeat = 1, [uint32] $Preheat = 0, [Hashtable] $Flag ) ... } ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `ScriptBlock` | `System.Management.Automation.ScriptBlock` | Yes | — | Script or script-file invocation to measure. | | `Repeat` | `uint32` | No | `1` | Number of measured repetitions. Values `<= 0` are coerced to `1`. | | `Preheat` | `uint32` | No | `0` | Warm-up runs (plain execution, no tracing). Values `<= 0` are coerced to `0`. During preheat, flags alternate `$false` on odd runs and hashtable values on even runs. | | `Flag` | `Hashtable` | No | `$null` | Feature flags; when provided each repetition runs twice — "Before" (all flags `$false`) then "After" (hashtable values) — and per-run pairs are printed as `Before -> After (Δ ms)` with green/red/yellow coloring by improvement. | ### Returns Nothing (no object output). Per-run timing is written with `Write-Host`: - `Run finished after ` / `Run - finished after ` - with `-Flag`, comparison lines: `Run : -> ( ms)` - errors in the measured code are caught per run and reported: `Run - failed after with .` ### Behavior - Calls `Assert-PowerShellVersion` first (throws on PowerShell majors other than 5/7). - Sets `$ErrorView = "Normal"` and `$ErrorActionPreference = "Stop"` locally. - Feature flags are applied as `$global:` variables before each run. - Does not use the tracer, so no `Profiler.Trace` is produced and `Get-LatestTrace` is not affected. ### Request Example ```powershell Import-Module Profiler Invoke-Script -ScriptBlock { Import-Module Pester; Invoke-Pester } -Repeat 3 # Output (host): # Run 1 finished after 00:00:12.340... # Run 2 finished after 00:00:11.100... # Run 3 finished after 00:00:11.050... ``` ### Request Example ```powershell # MyScript.ps1 wraps the new implementation in: if ($_profiler) { ... } else { ... } $flag = @{ _profiler = $true } Invoke-Script -ScriptBlock { & .\MyScript.ps1 } -Preheat 2 -Repeat 3 -Flag $flag # Output (host): # Run 1: 00:00:02.100 -> 00:00:01.400 (-700 ms) # Run 2: 00:00:02.050 -> 00:00:01.350 (-700 ms) # Run 3: 00:00:02.000 -> 00:00:01.300 (-700 ms) ``` ### Request Example ```powershell Invoke-Script -ScriptBlock { throw "boom" } -Repeat 2 # Output (host): # Run 1 failed after 00:00:00.001 with boom. # Run 2 failed after 00:00:00.001 with boom. # Done. try { Invoke-Script -ScriptBlock { 1 } } catch { # Only thrown for errors outside the measured code, # e.g. unsupported PowerShell version Write-Host "Invoke-Script failed: $_" } ``` ``` -------------------------------- ### Patch Source: https://github.com/nohwnd/profiler Activates tracing by hooking the session's UI host. Caller must run Set-PSDebug -Trace 1 before and Set-PSDebug -Off (or -Trace 0) after Unpatch. ```APIDOC ## Patch ### Description Activates tracing by hooking the session's UI host. Caller must run Set-PSDebug -Trace 1 before and Set-PSDebug -Off (or -Trace 0) after Unpatch. ### Method Patch ### Signature ```csharp public static void Patch(int powerShellVersion, EngineIntrinsics context, PSHostUserInterface ui, ITracer tracer) ``` ### Parameters - **powerShellVersion** (int) - Required - Major PS version (`$PSVersionTable.PSVersion.Major`); selects the internal UI field name: `"_externalUI"` for >= 6, `"externalUI"` for 5. - **context** (EngineIntrinsics) - Required - `$ExecutionContext`; null → `ArgumentNullException`. - **ui** (PSHostUserInterface) - Required - `$host.UI`; null → `ArgumentNullException`. - **tracer** (ITracer) - Required - The tracer; null → `ArgumentNullException`. ### Behavior 1. Stores `Tracer1 = tracer`. 2. Reflects the internal `InternalHostUserInterface` field, wraps the real external `PSHostUserInterface` in a `TracerHostUI` that forwards `WriteDebugLine` to `TraceLine`, and writes it back — `ResetUI` captures restoring the original. 3. Reflects the debugger internals (`_context`, `Debugger`, `_callStack`, `Count`, `LastFunctionContext`, `_functionName`, `_executionContext`, `SessionState`, `_scriptBlock`, `CurrentPosition`) and builds `GetTraceLineInfo` — a closure producing a `TraceLineInfo(extent, scriptBlock, level, functionName, moduleName)` per traced statement; `level` is the call-stack depth minus the depth at patch time. 4. Emits one extra trace line (`TraceLine()`) to make first runs consistent (per source comment). ``` -------------------------------- ### Error handling Source: https://github.com/nohwnd/profiler Wraps Export-SpeedScope in a try/catch to handle invalid export paths from Get-NextName (id exhaustion) or file I/O exceptions from the StreamWriter. Outputs a warning with the exception message. ```powershell try { Export-SpeedScope -Trace $trace -Path ./full } catch { Write-Warning "Export failed: $($_.Exception.Message)" } ``` -------------------------------- ### Which code is slow? Source: https://github.com/nohwnd/profiler/blob/main/presentation-v3/Profiler.pdf Use Top50SelfDuration and Top50Duration to identify slow code. ```text -Look at .Top50SelfDuration to see which code is slowest -Look at .Top50Duration to see which parts of your script take the most time, and decide if that is appropriate ``` -------------------------------- ### Show-ScriptExecution function signature Source: https://github.com/nohwnd/profiler Defines the function with a Trace parameter and slowdown switches x1, x10, x100, x1000. The switches are mutually exclusive in priority order x1000 > x100 > x10 > x1; with no switch, x = 0 and no sleeping occurs. The commented-out $Color switch and $blueToGreen branch are disabled. ```powershell function Show-ScriptExecution { [CmdletBinding()] param( $Trace, [switch] $x1, [switch] $x10, [switch] $x100, [switch] $x1000 # , # [switch] $Color ) ... } ``` -------------------------------- ### Retrieve trace after unassigned Trace-Script Source: https://github.com/nohwnd/profiler Shows how to use Get-LatestTrace when Trace-Script output was not assigned. The warning message indicates the need to assign or use Get-LatestTrace. ```powershell Trace-Script -ScriptBlock { & .\MyScript.ps1 } # Output: "Looks like you did not assign the output to a variable. # Use Get-LatestTrace to retrieve the trace, e.g.: $trace = Get-LatestTrace" $trace = Get-LatestTrace $trace.Top50Duration | Format-Table ``` -------------------------------- ### Drill into a raw event Source: https://github.com/nohwnd/profiler Traces a script, finds the first event whose text matches '*Invoke-WebRequest*', and prints its call stack with Text, Module, and Function fields. ```powershell $trace = Trace-Script { & .\MyScript.ps1 } $hit = $trace.Events | Where-Object { $_.Text -like '*Invoke-WebRequest*' } | Select-Object -First 1 Get-CallStack -hit $hit | Select-Object Text, Module, Function ``` -------------------------------- ### Catch Tracer.Unpatch corruption error in consumer code Source: https://github.com/nohwnd/profiler Shows how to catch the InvalidOperationException when driving the C# API directly. ```powershell try { [Profiler.Tracer]::Unpatch() } catch [System.InvalidOperationException] { Write-Warning "Tracing was broken by user code: $_" } ``` -------------------------------- ### Get-NextName throws when filename candidates exhausted Source: https://github.com/nohwnd/profiler Thrown when generating the template filename for speedscope export and all 10,000 candidates (0000–9999) already exist. Source: Profiler/Export-SpeedScope.ps1:62. Reachable via Trace-Script -ExportPath and Export-SpeedScope. ```powershell throw "Could not find next name for $Name, last name candidate: '$candidate'" ``` -------------------------------- ### Export-SpeedScope Source: https://github.com/nohwnd/profiler Exports a trace to a SpeedScope JSON file. The output path can be a directory (auto-generated filename) or a template with placeholder. ```APIDOC ## Export-SpeedScope ### Description Exports a trace to a SpeedScope JSON file. The output path can be a directory (auto-generated filename) or a template with placeholder. ### Method PowerShell function ### Parameters - **-Trace** (object) - Required - The trace object from Trace-Script. - **-Path** (string) - Required - Output directory or file template. If directory, file named profiler_.speedscope.json is created. ### Response Writes a SpeedScope JSON file to the specified path. ### Request Example ```powershell Import-Module Profiler $trace = Trace-Script { & .\demo-scripts\MyScript.ps1 } Export-SpeedScope -Trace $trace -Path ./report # ./report/profiler_0000.speedscope.json (id increments per run) ``` ``` -------------------------------- ### Profiler.Tracer.ShouldRegisterTracer Source: https://github.com/nohwnd/profiler Controls tracer registration behavior, allowing overwrite of existing tracers or placement in a secondary slot. ```APIDOC ## Profiler.Tracer.ShouldRegisterTracer ### Description Determines how a tracer is registered, with options to overwrite existing tracers or use a secondary slot. ### Parameters #### tracer - **Type**: `object` - **Required**: Yes - **Description**: The tracer to register. #### overwrite - **Type**: `bool` - **Default**: `true` - **Required**: No - **Description**: `true`: register into slot 1 replacing same-type tracers; `false`: always use slot 2 when slot 1 is occupied. ``` -------------------------------- ### Error handling when no trace exists Source: https://github.com/nohwnd/profiler Shows that Show-ScriptExecution performs no error handling; calling it before any Trace-Script run makes Get-LatestTrace warn and return nothing, causing a null dereference when $trace.Events is accessed. The catch block surfaces the error message, e.g. 'Cannot index into a null array'. ```powershell try { Show-ScriptExecution # no trace yet } catch { Write-Host "Cannot show execution: $($_.Exception.Message)" # e.g. 'Cannot index into a null array' } ``` -------------------------------- ### Get-NextName PowerShell helper function Source: https://github.com/nohwnd/profiler Resolves the next available `` filename. Default name template is `profiler_.speedscope.json`. Throws when all ids 0000–9999 are taken. ```powershell function Get-NextName { param( [Parameter(Mandatory)] [string] $Path, [string] $Name = 'profiler_.speedscope.json' ) } ``` -------------------------------- ### Assert-PowerShellVersion throws for unsupported PowerShell version Source: https://github.com/nohwnd/profiler Thrown when $PSVersionTable.PSVersion.Major is not 5 or 7. Called at the top of Trace-ScriptInternal and Invoke-Script. ```powershell throw "This module only supports PowerShell 5 and 7, but this is $($PSVersionTable.PSVersion)." ``` -------------------------------- ### Profile $profile script Source: https://github.com/nohwnd/profiler/blob/main/presentation-v3/Profiler.pdf Profile the user's $profile script using pwsh with -NoProfile -NoExit. ```powershell pwsh -NoProfile -NoExit { $trace = Trace-Script {. $Profile} } ``` -------------------------------- ### Error handling / defensive use Source: https://github.com/nohwnd/profiler Checks for a null trace and throws if none is available, then filters out internal events from the Events array. ```powershell $trace = Get-LatestTrace if ($null -eq $trace) { throw "No trace available." } # Events may contain internal events at indices 0, 1, count-2, count-1 $userEvents = $trace.Events[2..($trace.Events.Count - 3)] ``` -------------------------------- ### Run code multiple times with Invoke-Script for comparison Source: https://github.com/nohwnd/profiler/blob/main/README.MD Runs a script block multiple times with preheating disabled and repeats 3 times, using a flag to enable profiling. Useful for comparing performance before and after changes. ```powershell $flag = @{ _profiler = $true } Invoke-Script -ScriptBlock $scriptBlock -Preheat 0 -Repeat 3 -Flag $flag ``` -------------------------------- ### Trace-Script Source: https://github.com/nohwnd/profiler Runs a script under the profiler and returns a Profiler.Trace object with detailed performance data. The trace is always returned, even if the script throws, and extensive progress output is written to the host. ```APIDOC ## Trace-Script ### Description Runs a script under the profiler and returns a `Profiler.Trace` object containing detailed performance data. The trace is always returned, even when the profiled script throws, and extensive progress/status output is written to the host via `Write-Host`. ### Returns `[Profiler.Trace]` — see [trace.md](trace.md) for the full object shape (`Top50SelfDuration`, `Top50Duration`, `Top50HitCount`, `Top50FunctionDuration`, `Top50FunctionSelfDuration`, `Top50FunctionHitCount`, `Top50SelfMemory`, `Top50Memory`, `AllLines`, `Events`, `TotalDuration`, `StopwatchDuration`, `ScriptBlock`). The same object is stored in the module's `$script:processedTrace` and is also available via `Get-LatestTrace`. ### Behavior 1. Writes "Running in PowerShell *version* *bits*-bit." 2. Warns when `-Before` and `-After` are used together (uses `-After`). 3. Detects whether the invocation was assigned (`$x = Trace-Script …` via regex on `$MyInvocation.Line`); if not, prints a yellow hint to use `Get-LatestTrace`. 4. Delegates to `Trace-ScriptInternal` which: asserts the PowerShell version, applies `-Flag` globals, runs `Preheat` warm-ups, then runs the measured run through `Measure-ScriptHarmony`. 5. Runs the processing pipeline (`Profiler.ProcessFlow` → `Profiler.ProcessLines` → percent arithmetic → `Profiler.ProcessFunctions` → percent arithmetic), builds the 12 Top-50 collections, and assembles `Profiler.Trace` (see [profiler.md](profiler.md)). 6. `TotalDuration` = `trace[-2].Timestamp - trace[2].Timestamp` (first two and last two events are Profiler internals); `TotalMemory` analogous from `AllocatedBytes`. 7. Prints "Duration: A:/B: …" or a "Progress:" run history (last 5 runs, `B:`/`A:` markers, ms diff vs previous run, colored by improvement/worsening). 8. With `-ExportPath`, calls `Export-SpeedScope`. ``` -------------------------------- ### SpeedScopeFrame class Source: https://github.com/nohwnd/profiler Represents a frame with a Name property. Source: csharp/Profiler/SpeedScope/SpeedScopeFrame.cs. ```csharp public class SpeedScopeFrame { public string Name { get; set; } } ```