Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic with PowerShell Timespans

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?

like image 733
Ken Paul Avatar asked Aug 20 '10 23:08

Ken Paul


2 Answers

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
like image 88
Joey Avatar answered Sep 24 '22 21:09

Joey


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.

like image 22
JasonMArcher Avatar answered Sep 24 '22 21:09

JasonMArcher