Arithmetic with PowerShell Timespans
Asked Answered
W

4

6

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?

Wolfhound answered 20/8, 2010 at 23:55 Comment(0)
H
10

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
Hospitalet answered 21/8, 2010 at 6:57 Comment(1)
Great answer -- I gave this a slight edge over the other answer based on personal aesthetics.Wolfhound
I
4

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.

Iloilo answered 21/8, 2010 at 5:16 Comment(2)
Great answer -- I wish I could award two answersWolfhound
You know, it isn't that great afterall. It isn't truely measuring each iteration, just estimating.Iloilo
S
0

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
Stegall answered 27/9, 2017 at 19:42 Comment(1)
You could add to this pattern by counting the number of iterations made and then performing the average calculations at the end by dividing the total seconds by the loop count.Stegall
A
0

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) ) )
Algin answered 1/11 at 2:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.