Simple toggle trick

Share your advanced PureBasic knowledge/code with the community.
Randy Walker
Addict
Addict
Posts: 1035
Joined: Sun Jul 25, 2004 4:21 pm
Location: USoA

Re: Simple toggle trick

Post by Randy Walker »

Wow! I sure can stir things up. :oops:
- - - - - - - - - - - - - - - -
Randy
I *never* claimed to be a programmer.
User avatar
Piero
Addict
Addict
Posts: 894
Joined: Sat Apr 29, 2023 6:04 pm
Location: Italy

Re: Simple toggle trick

Post by Piero »

mk-soft wrote: Fri Aug 22, 2025 6:21 pm Short way for ASM and C backend

Code: Select all

Macro Toggle(x)
  x=~x&1
EndMacro
What about "x!1"?

Anyway that's just for the 1st bit :P
Last edited by Piero on Fri Aug 22, 2025 10:07 pm, edited 1 time in total.
AZJIO
Addict
Addict
Posts: 2165
Joined: Sun May 14, 2017 1:48 am

Re: Simple toggle trick

Post by AZJIO »

And now checking the speed.

Code: Select all

EnableExplicit
DisableDebugger

Define t, i, StartTime, t1, t2, t3, t4, t5, t6
#count = 10000000

t = 0
StartTime = ElapsedMilliseconds()
For i = 0 To #count
	t = ~ t
Next
t1 = ElapsedMilliseconds() - StartTime

t = 0
StartTime = ElapsedMilliseconds()
For i = 0 To #count
	t = Bool(Not t)
Next
t2 = ElapsedMilliseconds() - StartTime

t = 0
StartTime = ElapsedMilliseconds()
For i = 0 To #count
	t ! 1
Next
t3 = ElapsedMilliseconds() - StartTime

t = 0
StartTime = ElapsedMilliseconds()
For i = 0 To #count
	t = Bool(t = 0)
Next
t4 = ElapsedMilliseconds() - StartTime

t = 0
StartTime = ElapsedMilliseconds()
For i = 0 To #count
	t = Abs(t - 1)
Next
t5 = ElapsedMilliseconds() - StartTime

t = 0
StartTime = ElapsedMilliseconds()
For i = 0 To #count
	t=~t&1
Next
t6 = ElapsedMilliseconds() - StartTime

EnableDebugger

Debug t1
Debug t2
Debug t3
Debug t4
Debug t5
Debug t6
If the unsuccessful version showed a high speed, I would fix it at the start and then use it.

Code: Select all

t = 15

; correction
If t
	t=-1
EndIf

; Further proper use
For i = 0 To 5
	t = ~ t
	Debug t
Next
The readings are inaccurate, the penultimate for some reason always gives out more time. If I do it first, it works fast, and another fragment becomes slow.

I launched each individually several times and received the next speed rating (#count = 100000000).

Code: Select all

t=~t&1 ; 116-123
t = Bool(t = 0) ; 120-131
t = Bool(Not t) ; 133
t ! 1 ; 138
t = ~ t ; 140
t = Abs(t - 1) ; 500
Last edited by AZJIO on Fri Aug 22, 2025 10:29 pm, edited 3 times in total.
User avatar
Piero
Addict
Addict
Posts: 894
Joined: Sat Apr 29, 2023 6:04 pm
Location: Italy

Re: Simple toggle trick

Post by Piero »

Thanks to all!
I needed some refreshing on bitwise stuff (sometimes needs a LOT of attention to craft it properly…)
I "had forgot some rules"…

Hopeful PS:
AZJIO&Mac=%1
Post Reply