Flying Thunder
Flying Thunder

Reputation: 940

Powershell difference between 0.6 and 0.5 seconds feels weird

This isn not really a problem. It might not be directly caused by powershell, but I have encountered this weird phenomenon today. I even got bored and made a small script that clicks in a loop, so nothing serious.

Here is what is weird: When I added a small sleep into the loop to not have my system die due to gorrilions of clicks a second, I noticed a HUGE difference in frequency between:

sleep 0.50001 - it was clearly visible that it was clicking twice a second.

and

sleep 0.5 - was a LOT faster - it felt like at least 10 clicks a second.

I have tested this on the browser "game" cookie clicker to visualize this (okay, and to get rid of some boredom) and it got really obvious there.

To the question: Can anyone explain to me why 0.5 is apparently a lot faster than 0.50001 in powershell?

PS: I have tested it with 0.4, 0.6 too - its as if 0.5 is the border between normal and subsonic speed.

Upvotes: 1

Views: 1996

Answers (2)

tukan
tukan

Reputation: 17345

The issue is rounding as Jessen said.

There is one thing:

Sleep is not a PowerShell function it is a batch file's one (as Jessen correctly said it is also a PowerShell an alias to Start-Sleep do not confuse them.). Not to confuse them Microsoft probably decided to use Start-Sleep for PowerShell instead of simple Sleep and added alias for that.

If you want to do it the PowerShell way use Start-Sleep. You won't get confused if you add the -Milliseconds there:

Start-Sleep [-Seconds] <int>  [<CommonParameters>]
Start-Sleep -Milliseconds <int>  [<CommonParameters>]

To check that it is "only" alias

PS U:\> get-alias -name sleep

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Alias           sleep -> Start-Sleep

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174690

You're the victim of midpoint rounding!

Let's have a look at the syntax for Start-Sleep:

PS C:\> Get-Command Start-Sleep -Syntax

Start-Sleep [-Seconds] <int> [<CommonParameters>]

Start-Sleep -Milliseconds <int> [<CommonParameters>]

As you can see, the default parameter set takes the Seconds to sleep as an integer.

When you supply a Double, PowerShell tries to convert your input value to an integer, and 0.5 and below gets rounded to 0, thanks to the default midpoint rounding mode employed by .NET

So [int]0.50001 is equal to 1 and [int]0.5 is equal to 0

Upvotes: 7

Related Questions