Average Rating:

4.50 by 2 users.

31 Downloads, 70 Views

2 Comment(s)

get-ExecutionTime.ps1

By: Brian T Young 21 Apr 2011 06:57 PM UTC in the category: Beginner Event 10

Description:

This script will execute the specified scriptblock the number of runs specified and reports back the average time taken in milliseconds.

function get-ExecutionTime
{
<#
.SYNOPSIS
Measures average millisecond time it takes to run scriptblock provided.

.DESCRIPTION
This script will execute the specified scriptblock the number of runs specified and reports back the average time taken in milliseconds.

.PARAMETER Runs
Specifies the number of times to measure the execution time of the specified scriptblock.

.PARAMETER Command
Scriptblock that is being tested. Default is {start-sleep -seconds 5}

.EXAMPLE

PS C:\> get-ExecutionTime -runs 5 {start-sleep -seconds 5}

Description
-----------
Measures time taken to run scriptblock {start-sleep -seconds 5} 5 times and reports back average milliseconds.


.EXAMPLE

PS C:\> get-Executiontime -runs 3 {Get-EventLog application -Newest 5}

Description
-----------
Measures time taken to run scriptblock {Get-EventLog application -Newest 5} 3 times and reports back average milliseconds.

.EXAMPLE

PS C:\> get-Executiontime -runs 3 {Get-EventLog application -EntryType error -Newest 5}| Out-File c:\logs\timerun.txt -Append

Description
-----------
Measures time taken to run scriptblock {Get-EventLog application -EntryType error -Newest 5} 3 times and then writes and appends the output in to c:\logs\timerun.txt.


.NOTES
Author: Brian Young
Date:4/19/2011
Language: English
#>

#Define parameters.

param([Parameter(Mandatory=$True)]$runs,[Scriptblock]$command = {Start-Sleep -Seconds 5})

#open array for storing measure of each run.

$results = @()

#loop to run measure command the specified number of runs.

for($i=0;$i -ne $runs;$i++)
{
$results = $results + (Measure-Command -Expression $command)
}

#add up the time for each run.

foreach ($time in $results)

	{
		$timetaken = $timetaken + $time
	}
#compute average time taken.

$avgTime = (($timetaken.TotalMilliseconds)/$runs)

#write output.

write-output "Average time to run {$command} $runs times is $avgTime milliseconds."
}
Top

Comments:

4/21/2011 8:03 PM
Good script.. I like that you have wrapped everything in a function, and made an option to pass both a scriptblock in, and number of runs. I would have loved that you had put in a default number of runs though, so that one could run the script without parameters.
4/21/2011 8:25 PM
@Claus - Thank you for the feedback. Putting in a default run value was something I thought of after pushing the save button. :D So my rev 2 already has it in and I am trying to see how to alter the function so that I can pass multiple scriptblocks to it through the pipeline.