Average Rating:

4.50 by 2 users.

29 Downloads, 75 Views

1 Comment(s)

Beginner10_2011.ps1

By: Albert Fortes 21 Apr 2011 10:27 AM UTC in the category: Beginner Event 10

Description:

Calculate the average execution time of a command.
#requires -version 2.0

<# 
.SYNOPSIS 
    Calculate the average execution time of a command.

.NOTES 
    File Name  : Beginner10_2011.ps1 
    Author     : Albert Fortes Ribot albert.fortes@gmail.com
		
.EXAMPLE 
	C:\PS>  Measure-CommandEx {Start-Sleep -Seconds 5} -Verbose
	VERBOSE: Current execution time : [5002,7049]
	VERBOSE: Current execution time : [5006,4608]
	VERBOSE: Current execution time : [5006,5485]
	VERBOSE: Current execution time : [5006,5152]
	VERBOSE: Current execution time : [5007,2735]
	Average time of 5 runs of the command:[Start-Sleep -Seconds 5] is 5005,90058 milliseconds.
                                                
	Description
	-----------
	The command in this example shows the execution average time of 5 executions of the "Start-Sleep -Seconds 5" expression, and every execution time.

.EXAMPLE 
	C:\PS>  Measure-CommandEx {Start-Sleep -Seconds 1} -TimesToRun 10
	Average time of 10 runs of the command:[Start-Sleep -Seconds 1] is 1014,60274 milliseconds.
                                                
	Description
	-----------
	The command in this example shows the execution average time of 10 executions of the "Start-Sleep -Seconds 1" expression.
	
.PARAMETER Scriptblock
	Specifies the expression to be measured.

.PARAMETER TimesToRun
	Specifies the number of times that the expression will be executed. The default is '5'.
	


#> 
Function Measure-CommandEx()
{
	Param(
	[Parameter(
	Position=0,
	mandatory=$true)]
	[scriptblock] $Scriptblock,
		
	[Parameter(mandatory=$false)]
	[int]$TimesToRun=5
	)

	$TotalTime=0
	for ($index = 0; $index -lt $TimesToRun; $index++) 
	{

		$ExecutionTime=(Measure-Command $Scriptblock).TotalMilliseconds
		Write-Verbose ("Current execution time : [{0}]" -f $ExecutionTime)
		$TotalTime+=$ExecutionTime
		
	}

	Write-Host ("Average time of {0} runs of the command:[{1}] is {2} milliseconds." -f $TimesToRun,$Scriptblock,($TotalTime/$TimesToRun))
}
Top

Comments:

4/21/2011 1:59 PM
Good use of a function that allows parsing parameters to your function, I would have liked that you had put in a "default" scriptblock, so you could run the script without parameters.

Good you have added documentation to describe the need to pass in a script block.