Ken Paul
Ken Paul

Reputation: 5765

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?

Upvotes: 6

Views: 8657

Answers (4)

JimB2
JimB2

Reputation: 463

Not quite the question asked, but this example might be useful to someone landing here.

Subtracting one datetime from another ($t2-$t1) implicitly produces a timespan. The timespan has a totalseconds property that can be used in calculations.

Example: At datetime $t1, the process has completed $p1 process steps. At $t2, $p2 steps. There are $ptotal steps.

The estimated completion time:

$t1.AddSeconds( ($t2-$t1).totalseconds * ( ($ptotal-$p1) / ($p2-$p1) ) )

Upvotes: 0

Jim
Jim

Reputation: 1108

Ok, I tried to add this as a comment, but the formatting of the code was just to limited in the comment, so I'll make it as another answer.

I had a similar need, but I was looping over a collection and needing to measure 2 different operations on each element in the collection and wanted to sum up the total time it took for each operation.

Here is what I did:

$opATot = New-TimeSpan
$opBTot = New-TimeSpan
$myData | %{
   $opA = Measure-Command -Expression { do-op-a $_ }
   $opB = Measure-Command -Expression { do-op-b $_ }
   $opATot = $opATot.add( $opA )
   $opBTot = $opBTot.add( $opB )
}
"Op A took " + $opATot
"Op B took " + $opBTot

Upvotes: 0

Joey
Joey

Reputation: 354864

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

Upvotes: 10

JasonMArcher
JasonMArcher

Reputation: 15011

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.

Upvotes: 4

Related Questions