PowerShell 计时器/秒表准确性 [英] PowerShell timer/stopwatch accuracy
问题描述
我发现 System.Diagnostics.Stopwatch 类似乎存在可测量的不准确性,即使是在很短的时间段内(即 20 秒).对于编码为运行 20 秒的进程,我的进程显示的经过时间为 20.3+ 秒:
I find that the System.Diagnostics.Stopwatch class has what seems to be measurable inaccuracy, even over a short time period (i.e. 20 seconds). My process is showing an elapsed time of 20.3+ seconds for a process coded to run 20 seconds:
$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).我的代码有问题吗?
Is this kind of accuracy drift to be expected when using the Stopwatch class in PowerShell? It seems to increase disproportional to the time span (i.e. 10 seconds is off by 0.1 and 20 by 0.3). Is my code at fault?
推荐答案
问题是,你想做什么?如果您试图确定脚本运行需要多长时间,您应该使用秒表.但是,如果您尝试在指定时间段后启动新的命令序列,请使用 [System.Timers.Timer] 并为计时器对象上的已过事件注册一个事件.然后将注册事件的操作指定为您要完成的操作.
The question is, what are you trying to do? If you are trying to determine how long it takes a script to run, exactly, you should use the stopwatch. However, if you are trying to start a new sequence of commands after a specified period, use a [System.Timers.Timer] and register an event for the elapsed event on the timer object. Then specify the action of the registered event to what it you are trying to accomplish.
这篇关于PowerShell 计时器/秒表准确性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!