使用 PowerShell 时间跨度进行算术

发布于 2024-09-16 01:13:52 字数 300 浏览 5 评论 0原文

PowerShell 时间跨度非常适合快速显示持续时间,如下所示:

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

但是,如果我在该时间范围内进行了 $loopcount 次处理迭代,我如何将持续时间除以 $loopcount 以获得每次迭代的平均持续时间?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

疧_╮線 2024-09-23 01:13:52

如果这样做(如果您不需要脚本块的输出),一个稍微好一点的方法可能是:

1..$loopcount | ForEach-Object {
    Measure-Command {
        # do some processing here
    }
} | Measure-Object -Average TotalSeconds

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
萌面超妹 2024-09-23 01:13:52

到这里,您可以根据需要进行调整。

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

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

秒是为此使用的最佳单位。

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.

空宴 2024-09-23 01:13:52

好的,我尝试将其添加为注释,但代码的格式仅限于注释,所以我将其作为另一个答案。

我有类似的需求,但我正在循环一个集合,需要测量集合中每个元素的 2 个不同操作,并希望总结每个操作所需的总时间。

这是我所做的:

$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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文