views:

37

answers:

2

PowerShell Timespans are great for quickly displaying durations, as in:

$starttime = $(get-date)
{ do some processing here }
write-host "Duration: $((new-timespan $starttime $(get-date)).tostring())"

But if I did $loopcount iterations of processing during that timeframe, how do I divide the duration by $loopcount to get the average duration per iteration?

A: 

Here you go, you can tweak as needed.

$StartTime = Get-Date
{ <#do some processing here#> }

$TimeSpan = New-TimeSpan $StartTime (Get-Date)
$AverageTimeSpan = New-TimeSpan -Seconds ($TimeSpan.TotalSeconds / $LoopCount)

Seconds is the best unit to use for this.

JasonMArcher
Great answer -- I wish I could award two answers
Ken Paul
You know, it isn't that great afterall. It isn't truely measuring each iteration, just estimating.
JasonMArcher
+1  A: 

A slightly nicer way if doing this (if you don't need output from your script block) would probably be:

1..$loopcount | ForEach-Object {
    Measure-Command {
        # do some processing here
    }
} | Measure-Object -Average TotalSeconds
Joey
Great answer -- I gave this a slight edge over the other answer based on personal aesthetics.
Ken Paul