### Install Profiler Module Source: https://github.com/nohwnd/profiler/blob/main/README.MD Installs the Profiler module from the PowerShell Gallery. This is the first step to using the module's profiling capabilities. ```powershell Install-Module Profiler ``` -------------------------------- ### Install Profiler Module in PowerShell Source: https://context7.com/nohwnd/profiler/llms.txt Installs and imports the Profiler module from the PowerShell Gallery. It also includes a command to verify the installation by checking if the module is loaded. ```powershell # Install the Profiler module from PowerShell Gallery Install-Module Profiler # Import the module Import-Module Profiler # Verify installation Get-Module Profiler ``` -------------------------------- ### Identify Slowest Line and Get Call Stack (PowerShell) Source: https://context7.com/nohwnd/profiler/llms.txt Finds the line of code with the longest self-duration and retrieves its call stack. This helps pinpoint the origin of performance bottlenecks. ```powershell # Find a slow line $slowLine = $trace.Top50SelfDuration | Select-Object -First 1 # Get the call stack for the first hit of that line $hit = $slowLine.Hits[0] Get-CallStack -Hit $hit | Format-Table ``` -------------------------------- ### Get Call Stack with Get-CallStack in PowerShell Source: https://context7.com/nohwnd/profiler/llms.txt The Get-CallStack function retrieves the complete call stack for a specific hit in a trace generated by Trace-Script. This function is useful for understanding the execution path that led to a particular line of code being executed. ```powershell # Profile a script $trace = Trace-Script -ScriptBlock { & "./MyScript.ps1" } ``` -------------------------------- ### Implement Feature Flags for A/B Testing (PowerShell) Source: https://context7.com/nohwnd/profiler/llms.txt Demonstrates how to use feature flags within a script to conditionally execute different code paths, enabling A/B testing and performance comparison between code versions. ```powershell # In your script (MyScript.ps1), wrap code changes with feature flags: # # if ($_profiler) { # # New optimized code # $values = [System.Linq.Enumerable]::Range(1, 10000) # $result = foreach ($v in $values) { $v + 10 } # } # else { # # Original slow code # $values = 1..10000 # $result = @() # foreach ($v in $values) { $result += $v + 10 } # } # Compare performance with Invoke-Script $flag = @{ _profiler = $true } Invoke-Script -ScriptBlock { & "./MyScript.ps1" } -Repeat 5 -Flag $flag # Profile "after" changes $traceAfter = Trace-Script -ScriptBlock { & "./MyScript.ps1" } -Flag $flag $traceAfter.TotalDuration # e.g., 00:00:00.234 # Profile "before" changes (all flags set to $false) $traceBefore = Trace-Script -ScriptBlock { & "./MyScript.ps1" } -Flag $flag -Before $traceBefore.TotalDuration # e.g., 00:00:02.456 # Multiple independent flags for granular testing $flags = @{ _useLinq = $true _parallelProcessing = $false _cacheResults = $true } Invoke-Script -ScriptBlock { & "./MyScript.ps1" } -Repeat 3 -Flag $flags ``` -------------------------------- ### Analyze Trace Results for Performance Bottlenecks (PowerShell) Source: https://context7.com/nohwnd/profiler/llms.txt Provides various methods to explore the trace object returned by Trace-Script, including accessing top performers by duration, hit count, and memory usage, as well as filtering and drilling into specific events. ```powershell # Profile a script $trace = Trace-Script -ScriptBlock { & "./MyScript.ps1" } # Explore available properties $trace | Get-Member # Top 50 views available: $trace.Top50Duration # Lines by total duration (including called code) $trace.Top50SelfDuration # Lines by self duration (excluding called code) $trace.Top50HitCount # Lines by execution count $trace.Top50FunctionDuration # Functions by total duration $trace.Top50FunctionSelfDuration # Functions by self duration $trace.Top50FunctionHitCount # Functions by call count $trace.Top50SelfMemory # Lines by memory allocation $trace.Top50Memory # Lines by total memory # Drill into a specific slow line $slowLine = $trace.Top50Duration | Where-Object Text -match 'Invoke-WebRequest' $slowLine | Format-List # See all hits (executions) of that line $slowLine.Hits | Format-Table # Analyze what happened between a function call and its return $hit = $slowLine.Hits[0] $trace.Events[$hit.Index..$hit.ReturnIndex] | Format-Table # Find top consumers within a specific call $trace.Events[$hit.Index..$hit.ReturnIndex] | Sort-Object -Descending SelfDuration | Select-Object -First 10 | Format-Table # Filter all lines by file $trace.AllLines | Where-Object Path -like '*MyModule*' | Format-Table # Get total execution time $trace.TotalDuration # Access raw events for custom analysis $trace.Events | Where-Object { $_.SelfDuration.TotalMilliseconds -gt 10 } | Sort-Object -Descending SelfDuration | Format-Table Path, Line, Text, SelfDuration ``` -------------------------------- ### Profile Script Blocks with Memory Tracking in PowerShell Source: https://context7.com/nohwnd/profiler/llms.txt This snippet demonstrates how to profile a PowerShell script block, including tracking memory allocation. It highlights inefficient array concatenation versus efficient List.Add() for memory management and shows how to view top memory consumers and filter lines with high memory allocation. ```powershell $trace = Trace-Script -ScriptBlock { $list = [System.Collections.Generic.List[int]]::new() # Inefficient: array concatenation creates new array each iteration $array = @() foreach ($i in 1..1000) { $array += $i # High memory allocation } # Efficient: List.Add() modifies in place foreach ($i in 1..1000) { $list.Add($i) # Low memory allocation } # Memory-intensive operation $processes = Get-Process } # View top memory consumers $trace.Top50SelfMemory | Format-Table # View total memory by line (including called code) $trace.Top50Memory | Format-Table # Filter lines with high memory allocation $trace.AllLines | Where-Object { $_.SelfMemory -gt 1MB } | Sort-Object -Descending SelfMemory | Format-Table Path, Line, Text, SelfMemory, SelfMemoryPercent ``` -------------------------------- ### Visualize Script Execution Flow (PowerShell) Source: https://context7.com/nohwnd/profiler/llms.txt Displays the execution flow of a script with indentation reflecting call depth and color-coded timing. It can simulate different slowdowns for better analysis. ```powershell # Profile and visualize execution $trace = Trace-Script -ScriptBlock { & "./MyScript.ps1" } # Show execution flow (instant display) Show-ScriptExecution -Trace $trace # Show execution with 10x slowdown to mimic real timing Show-ScriptExecution -Trace $trace -x10 # Show execution with 100x slowdown Show-ScriptExecution -Trace $trace -x100 # Use without specifying trace (uses Get-LatestTrace) Trace-Script -ScriptBlock { & "./MyScript.ps1" } Show-ScriptExecution ``` -------------------------------- ### Run Script Multiple Times for Comparison Source: https://github.com/nohwnd/profiler/blob/main/README.MD Executes a scriptblock multiple times with a specified number of repetitions and preheating iterations, using a flag to enable profiling. This is useful for comparing performance before and after code changes. ```powershell $scriptBlock = { Import-Module Pester Invoke-Pester } $flag = @{ _profiler = $true } Invoke-Script -ScriptBlock $scriptBlock -Preheat 0 -Repeat 3 -Flag $flag ``` -------------------------------- ### Trace Script Execution and Export Results Source: https://github.com/nohwnd/profiler/blob/main/README.MD Traces the execution of a scriptblock, capturing performance data and exporting it to a specified path in a format compatible with speedscope.app. This allows for detailed analysis of script performance and visualization. ```powershell $trace = Trace-Script -ScriptBlock { & "demo-scripts/Get-Icons.ps1" } -ExportPath icons $trace.Top50SelfDuration ``` -------------------------------- ### Memory Profiling for Allocation Analysis (PowerShell) Source: https://context7.com/nohwnd/profiler/llms.txt Enables tracking of memory allocation per line and function, helping to identify memory-intensive operations and potential memory leaks within the script's execution. ```powershell # Memory profiling is typically done by accessing properties like: # $trace.Top50SelfMemory # $trace.Top50Memory # These properties would be populated after running Trace-Script. ``` -------------------------------- ### Profile PowerShell Script Execution with Trace-Script Source: https://context7.com/nohwnd/profiler/llms.txt The Trace-Script function profiles PowerShell scripts and ScriptBlocks, capturing detailed timing data for each line and function. It supports exporting results to speedscope.app format, profiling module functions, and using feature flags for before/after comparisons and warmup runs. ```powershell # Basic profiling of a script file $trace = Trace-Script -ScriptBlock { & "./MyScript.ps1" } # View top 50 lines by self-duration (time spent in the line itself) $trace.Top50SelfDuration | Format-Table # View top 50 lines by total duration (including called code) $trace.Top50Duration | Format-Table # View top 50 most frequently executed lines $trace.Top50HitCount | Format-Table # View top 50 functions by duration $trace.Top50FunctionDuration | Format-Table # View top 50 functions by self-duration $trace.Top50FunctionSelfDuration | Format-Table # Profile with export to speedscope.app format $trace = Trace-Script -ScriptBlock { & "./MyScript.ps1" } -ExportPath "profile.speedscope.json" # Profile a module function $trace = Trace-Script -ScriptBlock { Import-Module Pester Invoke-Pester -Path "./tests" } # Profile with feature flags for before/after comparison # In your script, wrap new code in: if ($_profiler) { } else { } $trace = Trace-Script -ScriptBlock { & "./MyScript.ps1" } -Flag @{ _profiler = $true } # Run with "before" code (all flags set to $false) $traceBefore = Trace-Script -ScriptBlock { & "./MyScript.ps1" } -Flag @{ _profiler = $true } -Before # Profile with warmup runs (useful for accurate measurement excluding startup) $trace = Trace-Script -ScriptBlock { & "./MyScript.ps1" } -Preheat 2 ``` -------------------------------- ### Export PowerShell Profiling Results to SpeedScope Format Source: https://context7.com/nohwnd/profiler/llms.txt This section shows how to export profiling data generated by Trace-Script into the SpeedScope JSON format. It covers exporting during profiling with a specified path, exporting to a directory, using filename templates for auto-incrementing files, and exporting an existing trace object. ```powershell # Export during profiling $trace = Trace-Script -ScriptBlock { & "./MyScript.ps1" } -ExportPath "profile.speedscope.json" # Export to a specific directory (auto-generates filename) $trace = Trace-Script -ScriptBlock { & "./MyScript.ps1" } -ExportPath "./profiles/" # Use template for auto-incrementing filenames $trace = Trace-Script -ScriptBlock { & "./MyScript.ps1" } -ExportPath "run_.speedscope.json" # Creates: run_0000.speedscope.json, run_0001.speedscope.json, etc. # Export existing trace $trace = Trace-Script -ScriptBlock { & "./MyScript.ps1" } # ... analyze trace ... $trace | Export-SpeedScope -Path "analysis.speedscope.json" # View in browser: Open https://speedscope.app/ and drag the .speedscope.json file ``` -------------------------------- ### Profile a ScriptBlock with Pester Source: https://github.com/nohwnd/profiler/blob/main/README.MD Profiles the execution of a scriptblock that imports and runs Pester tests. This is useful for analyzing the performance of test suites. ```powershell $scriptBlock = { Import-Module Pester Invoke-Pester } Trace-Script -ScriptBlock $scriptBlock ``` -------------------------------- ### Retrieve Latest Trace Data Source: https://github.com/nohwnd/profiler/blob/main/README.MD Retrieves the most recent trace data when the output of Invoke-Script was not assigned to a variable. This allows access to performance metrics like Top50Duration. ```powershell Invoke-Script -ScriptBlock $scriptBlock -Preheat 0 -Repeat 3 -Flag $flag # 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 ``` -------------------------------- ### Measure PowerShell Script Execution Time with Invoke-Script Source: https://context7.com/nohwnd/profiler/llms.txt The Invoke-Script function measures script execution time without detailed tracing, suitable for quick performance comparisons and benchmarking. It supports multiple repetitions, feature flags for before/after comparisons, and warmup runs. ```powershell # Basic execution timing with 3 repetitions Invoke-Script -ScriptBlock { & "./MyScript.ps1" } -Repeat 3 # Compare before and after performance with feature flags # Your script should contain: if ($_profiler) { } else { } $flag = @{ _profiler = $true } Invoke-Script -ScriptBlock { & "./MyScript.ps1" } -Preheat 2 -Repeat 5 -Flag $flag # Output shows color-coded comparison: # Run 1: 00:00:00.5234 -> 00:00:00.3127 (-210 ms) # Green = improvement # Run 2: 00:00:00.4891 -> 00:00:00.2984 (-191 ms) # Run 3: 00:00:00.5012 -> 00:00:00.3056 (-196 ms) # Use multiple feature flags for granular testing $flags = @{ _useLinq = $true # Test LINQ vs native _parallelLoop = $true # Test parallel processing } Invoke-Script -ScriptBlock { & "./MyScript.ps1" } -Repeat 3 -Flag $flags ``` -------------------------------- ### Retrieve Latest Trace with Get-LatestTrace in PowerShell Source: https://context7.com/nohwnd/profiler/llms.txt The Get-LatestTrace function retrieves the most recent trace data when the output of Trace-Script was not assigned to a variable. This is useful for interactive analysis without re-running profiling operations and allows access to all profiled lines and raw trace events. ```powershell # Run profiling without capturing output Trace-Script -ScriptBlock { & "./MyScript.ps1" } # Output: "Looks like you did not assign the output to a variable..." # Retrieve the trace afterward $trace = Get-LatestTrace # Now explore the results $trace.Top50SelfDuration | Format-Table $trace.Top50FunctionDuration | Format-Table # Access all profiled lines $trace.AllLines | Where-Object { $_.Duration.TotalMilliseconds -gt 100 } | Format-Table # Access raw trace events $trace.Events | Select-Object -First 10 | Format-Table ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.