1- function Get -AverageExecutionTime {
1+ function Measure -AverageExecutionTime {
22 <#
33 . SYNOPSIS
44 Get the average execution time for running a script block multiple times.
@@ -13,11 +13,18 @@ function Get-AverageExecutionTime {
1313
1414 . EXAMPLE
1515 [scriptblock]$Scriptblock = { $TypeAccelerators = [System.Management.Automation.PSObject].Assembly.GetType("System.Management.Automation.TypeAccelerators")::Get | Sort-Object }
16- Get -AverageExecutionTime $Scriptblock
16+ Measure -AverageExecutionTime $Scriptblock
1717
18+ . EXAMPLE
19+ [scriptblock]$Scriptblock = { Get-Process | Where-Object CPU -gt 10 }
20+ Measure-AverageExecutionTime -Scriptblock $Scriptblock -Count 100 -Verbose
21+
22+ . LINK
23+ Measure-Command
24+ https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/measure-command
1825 #>
1926 [CmdletBinding ()]
20- [OutputType ([double ])]
27+ [OutputType ([PSCustomObject ])]
2128 param (
2229 [Parameter (
2330 Mandatory = $true ,
@@ -29,23 +36,35 @@ function Get-AverageExecutionTime {
2936 Mandatory = $false ,
3037 HelpMessage = ' Specify the number of times to run the scriptblock. (Default 50)'
3138 )]
39+ [ValidateRange (1 , [int ]::MaxValue)]
3240 [int ]$Count = 50
3341 )
3442
3543 begin {
3644 [timespan ]$TotalTime = New-TimeSpan
45+ [double ]$MinTime = [double ]::MaxValue
46+ [double ]$MaxTime = 0
3747 }
3848
3949 process {
4050 # Run the command $Count times
4151 for ($i = 0 ; $i -lt $Count ; $i ++ ) {
4252 # Measure the execution time
4353 $RunTime = Measure-Command - Expression { $Scriptblock.Invoke () }
54+ $RunTimeMs = $RunTime.TotalMilliseconds
4455
45- Write-Verbose " The total runtime for run $ ( $i + 1 ) was $ ( $RunTime .TotalMilliseconds ) ms."
56+ Write-Verbose " The total runtime for run $ ( $i + 1 ) was $RunTimeMs ms."
4657
4758 # Add the execution time to the total time
4859 $TotalTime = $TotalTime.Add ($RunTime )
60+
61+ # Track minimum and maximum times
62+ if ($RunTimeMs -lt $MinTime ) {
63+ $MinTime = $RunTimeMs
64+ }
65+ if ($RunTimeMs -gt $MaxTime ) {
66+ $MaxTime = $RunTimeMs
67+ }
4968 }
5069
5170 # Calculate the average execution time in milliseconds
@@ -54,6 +73,14 @@ function Get-AverageExecutionTime {
5473
5574 end {
5675 Write-Verbose " The average execution time for your scriptblock was $AverageTime ms."
57- return $AverageTime
76+
77+ # Return detailed statistics
78+ [PSCustomObject ]@ {
79+ AverageMilliseconds = $AverageTime
80+ TotalMilliseconds = $TotalTime.TotalMilliseconds
81+ MinimumMilliseconds = $MinTime
82+ MaximumMilliseconds = $MaxTime
83+ Iterations = $Count
84+ }
5885 }
5986}
0 commit comments