I thought negating a word or XOR a word with 1 both should take 1 clock cycle of the processor, but if using Python3, the following code to count the parity of a word:
def parity(x: int) -> int:
p = 0
while x:
p = ~p
x = x & (x-1)
return p & 1
running against 10,000 test cases would report 4μs average running time consistently, but if it is:
def parity(x: int) -> int:
p = 0
while x:
p = p ^ 1
x = x & (x-1)
return p
then it is consistently 5μs. It actually has one less operation at the end not needing to & 1.
Even
def parity(x: int) -> int:
p = 0
while x:
p += 1
x = x & (x-1)
return p % 2
is consistently running for 4μs. To test increment vs addition, I changed the p += 1 to p += 7 and it is again consistently 4μs. What is the reason negating, increment, or addition faster than XOR using Python3? (it is on a Mac if it makes any difference).