@@ -7,14 +7,17 @@ function Get-AverageExecutionTime {
77 Get the average time that it takes to execute a scriptblock. By default, the script block is run 50 times.
88
99 . NOTES
10-
10+ Author: Sam Erde
11+ Version: 1.1
12+ Date: 2026-01-05
1113
1214 . EXAMPLE
13- [scriptblock]$Scriptblock = { $TypeAccellerators = [System.Management.Automation.PSObject].Assembly.GetType("System.Management.Automation.TypeAccelerators")::Get | Sort-Object }
14- Get-AvgExecutionTime $Scriptblock
15+ [scriptblock]$Scriptblock = { $TypeAccelerators = [System.Management.Automation.PSObject].Assembly.GetType("System.Management.Automation.TypeAccelerators")::Get | Sort-Object }
16+ Get-AverageExecutionTime $Scriptblock
1517
1618 #>
1719 [CmdletBinding ()]
20+ [OutputType ([double ])]
1821 param (
1922 [Parameter (
2023 Mandatory = $true ,
@@ -36,31 +39,21 @@ function Get-AverageExecutionTime {
3639 process {
3740 # Run the command $Count times
3841 for ($i = 0 ; $i -lt $Count ; $i ++ ) {
39- # Get the current time before execution
40- $StartTime = Get-Date
41-
42- # Execute the command
43- $Scriptblock.Invoke ()
44-
45- # Get the current time after execution
46- $EndTime = Get-Date
47-
48- $RunTime = New-TimeSpan - Start $StartTime - End $EndTime
49- Write-Verbose " The total runtime for run $ ( $i + 1 ) was $ ( $RunTime.TotalMilliseconds ) ."
42+ # Measure the execution time
43+ $RunTime = Measure-Command - Expression { $Scriptblock.Invoke () }
5044
51- # Or.....just use this!
52- # $RunTime = Measure-Command -Expression { $Scriptblock.Invoke() }
45+ Write-Verbose " The total runtime for run $ ( $i + 1 ) was $ ( $RunTime.TotalMilliseconds ) ms."
5346
54- # Calculate the execution time and add it to the total time
47+ # Add the execution time to the total time
5548 $TotalTime = $TotalTime.Add ($RunTime )
5649 }
5750
58- # Calculate the average execution time
59- $AverageTime = $ ( $ TotalTime.Milliseconds ) / $Count
51+ # Calculate the average execution time in milliseconds
52+ $AverageTime = $TotalTime.TotalMilliseconds / $Count
6053 }
6154
6255 end {
63- Write-Verbose " The average execution time for your scriptblock was $ ( $ AverageTime.Milliseconds ) ms."
64- Return $AverageTime
56+ Write-Verbose " The average execution time for your scriptblock was $AverageTime ms."
57+ return $AverageTime
6558 }
6659}
0 commit comments