gpt4 book ai didi

PowerShell 计时器/秒表准确性

转载 作者:行者123 更新时间:2023-12-04 00:03:16 31 4
gpt4 key购买 nike

我发现 System.Diagnostics.Stopwatch 类即使在很短的时间段(即 20 秒)内似乎也存在可测量的不准确性。对于编码为运行 20 秒的进程,我的进程显示耗时为 20.3+ 秒:

$elapsed = [System.Diagnostics.Stopwatch]::StartNew()
write-host "Started at $(get-date)"

for ($t=1; $t -le 20; $t++) {
Write-Host "Elapsed Time: $($elapsed.Elapsed.ToString())"
sleep 1
}

write-host "Ended at $(get-date)"
write-host "Total Elapsed Time: $($elapsed.Elapsed.ToString())"

Started at 02/02/2013 15:08:43
Elapsed Time: 00:00:00.0329924
Elapsed Time: 00:00:01.0417435
Elapsed Time: 00:00:02.0547547
Elapsed Time: 00:00:03.0689716
Elapsed Time: 00:00:04.0820497
Elapsed Time: 00:00:05.0963413
Elapsed Time: 00:00:06.1113915
Elapsed Time: 00:00:07.1244044
Elapsed Time: 00:00:08.1396105
Elapsed Time: 00:00:09.1528952
Elapsed Time: 00:00:10.1659905
Elapsed Time: 00:00:11.1800884
Elapsed Time: 00:00:12.1940009
Elapsed Time: 00:00:13.2081824
Elapsed Time: 00:00:14.2223585
Elapsed Time: 00:00:15.2375023
Elapsed Time: 00:00:16.2506360
Elapsed Time: 00:00:17.2656845
Elapsed Time: 00:00:18.2790676
Elapsed Time: 00:00:19.2928700
Ended at 02/02/2013 15:09:04
Total Elapsed Time: 00:00:20.3080067

在 PowerShell 中使用 Stopwatch 类时是否会出现这种精度漂移?它似乎与时间跨度不成比例地增加(即 10 秒减少 0.1,20 秒减少 0.3)。我的代码有问题吗?

最佳答案

您有 20 次 1 秒的停顿,但您还有其他事情要做。有一个循环递增并测试一个变量,您可以在每次迭代中写入耗时。这些额外的事情需要时间。

这仍然有 20 秒的暂停,耗时接近 20 秒,因为 PowerShell 必须做的额外事情更少:

$elapsed = [System.Diagnostics.Stopwatch]::StartNew()
write-host "Started at $(get-date)"
sleep 20
write-host "Ended at $(get-date)"
write-host "Total Elapsed Time: $($elapsed.Elapsed.ToString())"

关于PowerShell 计时器/秒表准确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14668090/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com