Anyone know why this timer is off?

Hello,
Can anyone say why this timer script is off a bit?

$timer = New-Object System.Diagnostics.Stopwatch
$seconds -eq 0
do
{
$seconds = ($timer.elapsed.totalseconds)
$timer.start()
$seconds
Start-Sleep -Milliseconds 1000
}
until ($timer.elapsed.minutes -eq 59)
$timer.elapsed.minutes

Output:

False
0
1.0118032
2.0162498
3.0236591
4.029671
5.0310328
6.0408992
7.0432709

After ~130 seconds it skips a second due to the timing

What exactly do you mean? What do you expect?

Do you mean this:

101,9591559
102,9737869
 103,9898191
 105,0034982
106,0189042
107,0333377

?

It does not skip one second. Your loop takes a little bit more than a second. And when the loop iteration starts “at the end” of a second it will need until “the start” of the second after the next second. … so from 103,9898191 to 105,0034982.

Or did I get everything wrong? :thinking:

1 Like

Well, after I do $timer.start(), it starts at 1.0118032.
Then sleeps 1 second, and output is 2.0162498.

Thats more than 1 second?

1 other thing…
When I run it 2 times in a row, I get slightly different output. Why is that?

False
0
1.0092845
2.0147815
3.0197994

False
0
1.0140531
2.0195799
3.0221682

Are you really asking if 2.0162498 minus 1.0118032 is greater than 1? :face_with_raised_eyebrow: you can do the math … :wink:

Because this world is non-deterministic and there is very likely more running on your computer than just the PowerShell session. :man_shrugging:t4:

1 Like

What is actually your issue? Do you try to solve a particular problem? :thinking:

PowerShell and Windows in general are not supposed to be used for precise time measurements. Windows is not a real time OS. And you may consider that it takes time to run code - even if it’s just a small amount.
Doing a Start-Sleep -Milliseconds 1000 will probably take almost exactly 1 second. But doing a Write-Host as the next command in your loop will already take some more milliseconds. So if you run this a thousand times of course it will be more than 1000 seconds. :man_shrugging:t4: Is that really so suprising for you? You may run a loop with only a Start-Sleep in it and then a loop togehter with a Write-Host in it and compare them. :point_up_2:t4: :wink:

Complete agreement with Olaf. I would also point out that every line of code takes a small slice of time to execute so after you have slept for 1 second you have 4 other lines of code that need to execute before you see the next increase. Those take time and honestly outputting to a screen is slow in comparison to how fast a computer operates.