Average Rating:

4.50 by 2 users.

46 Downloads, 178 Views

1 Comment(s)

Get-AverageRunTime

By: Jay Morris - Moreski 21 Apr 2011 10:54 PM UTC in the category: Beginner Event 10

Description:

My submission to Beginner Event 10....
Moreski crosses the finish line :-)
function Get-AverageRunTime () {
<#
.SYNOPSIS
A Windows PowerShell function that calculates the average run time of a given expression / command / script.

.DESCRIPTION
This function will calculat the average run time of an expression a number of times. By default the function will calculate the 
average of five consecutive runs of the Start-Sleep command (Set to five seconds). The output will simply be the calculated 
average time taken to run each in turn.

.NOTES
    NAME: Get-AverageRunTime
          AUTHOR:  Jay Moreski
          VERSION HISTORY:
          1.0.0 00/21/2011 - Initial release
          1.0.0 00/21/2011 - Submission release

.PARAMETER  Count 
Use this parameter to set the mumber of times you wish to run the expression. 
Default = 5

.PARAMETER  Expression
Use this parameter to set expression that you wish to perform the calculation on. 
Default = "Get-Sleep -Seconds 5"
  
.EXAMPLE
 Get-AverageRunTime
 This will calculate and report the average run time to sleep a script for 5 seconds, Five times.

.EXAMPLE     
 Get-AverageRunTime -Count 10 -Expression "Get-WinEvent -ListLog *"
This will calculate and report the average run time to sleep a script for 5 seconds.

#>

   Param(
   $Count = 5 ,
   $Expression = "Start-Sleep -Seconds 5"
   )
   Write-Host "Performing mesurements... Please wait...." -ForegroundColor Yellow
    
    $TimeTaken = Measure-Command -Expression { 
        for ($index = 0; $index -lt $count; $index++) {
        Invoke-Expression $Expression
        }
    }
   $Average = ($TimeTaken.TotalMilliseconds) / ($Count) # Average Calculation [$TimeTaken.TotalMilliseconds = the Sum total of time taken divided be the count]
   Write-Host " The Average time taken to run the expression " -NoNewline ; Write-Host "$Expression " -ForegroundColor Green -NoNewline ; Write-Host "$Count times is $Average Milliseconds."
}
Top

Comments:

4/22/2011 12:15 AM
Consider using write-progress to provide progress notification. It is easy to use, and I have several Hey Scripting Guy! articles about using it. Your yellow is hard to read against the default ISE background. Nice script, great job.