發現System.Diagnostics.Stopwatch類即使在很短的時間段(即20秒)內似乎仍有明顯的不準確性。我的過程中呈現出20.3+秒編碼的過程中經過時間滑槽20秒:Powershell計時器/秒錶準確度
$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中的秒錶類時預期的?似乎與時間跨度不成比例地增加(即,10秒關閉0.1和20 0.3)。我的代碼有錯嗎?
擺脫開始和結束寫入主機調用,它應該更接近。秒錶使用Windows的高頻計數器API,因此它非常準確。 –
雷納恩,那將是20秒。但它不再是一個秒錶 - 只是一個睡眠計時器。這將阻止我的腳本運行,直到完成睡眠。我需要它來運行一個流程,最後告訴我需要多長時間才能完成。 –
我想你錯過了我的例子。我試圖表明'Diagnostics.Stopwatch'類不是不準確的。您腳本中的秒錶顯示「20.3080067」秒的原因是因爲您的腳本除了睡覺之外還在做其他事情。此外,「Get-Date」語句看起來恰好相隔20秒的原因是因爲顯示的時間四捨五入到最接近的秒數。 – Rynant