Page 1 of 1

Bool vs. If

Posted: Thu Jul 28, 2022 3:24 am
by jacdelad
Hi #PB_All,
I experimented with the question whether If or Bool is faster in the following example:

Code: Select all

DisableDebugger

Define a=10,b,c,tick1.q,tick2.q,tick3.q

tick1=ElapsedMilliseconds()

For b=1 To 1000000000
  c=Bool(a=10)
Next

tick2=ElapsedMilliseconds()

For b=1 To 1000000000
  If a=10
    c=1
  EndIf
Next

tick3=ElapsedMilliseconds()

EnableDebugger
Debug "Bool: "+Str(tick2-tick1)
Debug "If:   "+Str(tick3-tick2)
On my computer (Windows 10) Bool is a bit faster (1549ms vs. 1712ms). Is this always the case, on all platforms?

Also, the following code has an even wider gap between the results:

Code: Select all

DisableDebugger

Define a=10,b,c,tick1.q,tick2.q,tick3.q

tick1=ElapsedMilliseconds()

For b=1 To 1000000000
  c=5*Bool(a=10)
Next

tick2=ElapsedMilliseconds()

For b=1 To 1000000000
  If a=10
    c=50
  EndIf
Next

tick3=ElapsedMilliseconds()

EnableDebugger
Debug "Bool: "+Str(tick2-tick1)
Debug "If:   "+Str(tick3-tick2)
...which is somehow interesting, because I thought the *-operation would take more time than just storing a value.

Re: Bool vs. If

Posted: Thu Jul 28, 2022 4:20 am
by idle
The time difference is totally insignificant, what's more important is the effects that an IF or bool can have on the branching within your program and that's a whole conversation of itself, which is what Out of order execution can do for your code, if you can satisfy the branch prediction you will get cycles for free. An If is better for the branch prediction than a bool as far as I'm aware.

Re: Bool vs. If

Posted: Thu Jul 28, 2022 6:48 am
by STARGĂ…TE
If I replace the debug with PrintN and disable the whole debugger, both codes have exactly the same execution time:
Bool: 1513
If: 1539
However, please keep in mind, this time is mainly used by the loop. See this example:

Code: Select all

Define a=10,b,c,tick0.q,tick1.q,tick2.q,tick3.q

tick0=ElapsedMilliseconds()

For b=1 To 1000000000
  c=0
Next

tick1=ElapsedMilliseconds()

For b=1 To 1000000000
  c=Bool(a=10)
Next

tick2=ElapsedMilliseconds()

For b=1 To 1000000000
  If a=10
    c=1
  EndIf
Next

tick3=ElapsedMilliseconds()

OpenConsole()
PrintN("Loop: "+Str(tick1-tick0))
PrintN("Bool: "+Str(tick2-tick1))
PrintN("If:   "+Str(tick3-tick2))
Input()

Loop: 1227
Bool: 1423
If: 1451