A neat way of avoiding this if statement would be to have player_1 == 1 and player_2 == -1. At the end of each turn, multiply the number by -1.
I'd imagine it doesn't make much of a difference here (I mean if you really cared about performance you wouldn't be using Python), but "if" statements can screw up pipelining, which, for not-so-trivial programs, can dramatically slow down execution.
This also works, but the modulus operator involves division. If the compiler doesn't recognize %2 as logically equivalent to a bitwise operation on the least significant bit then this might slow things down.
Multiplication is as simple as several adders chained together with some bit-shifting for their inputs, and you could somewhat easily implement this algorithm entirely in hardware such that any two 64 bit ints could be multiplied together in a single cycle (floats would be slightly more complicated, but more or less the same).
Meanwhile, division is very complicated (relative to the other 3 fundamental arithmetic operations you learn in grade school, anyway), and there are many different algorithms out there which can get the job done. The naive approaches converge linearly, and some of the more interesting ones do it quadratically, but in any case division is likely to be a multi-cycle operation. In other words, slow.
View all comments
Show parent comment
3
u/EvilStevilTheKenevil May 12 '22
A neat way of avoiding this if statement would be to have player_1 == 1 and player_2 == -1. At the end of each turn, multiply the number by -1.
I'd imagine it doesn't make much of a difference here (I mean if you really cared about performance you wouldn't be using Python), but "if" statements can screw up pipelining, which, for not-so-trivial programs, can dramatically slow down execution.