Hacker News new | ask | show | jobs
by jackdied 6652 days ago
Clever, but as others pointed out likely to anger anyone who has to read your code.

NB: python bitwise operations are not super fast like in C. They don't get optimized down to single CPU instructions but instead are looked up like regular type methods (e.g. __str__ and __add__). An "ob[~0]" won't kill you even in a loop but don't bother translating simple math into bit-twiddling because it won't help (and might hurt if it inflates the number of operations).

3 comments

I tried profiling these two functions:

  import cProfile
  
  def flipbits():
      c=0
      for i in range(1,400000):
          b=~i
          c=c+b
      print c

  def negnums():
      c=0
      for i in range(1,400000):
          b=-i
          c=c+b
      print c

  cProfile.run("flipbits()")
140 function calls in 0.175 CPU seconds

  cProfile.run("negnums()")
140 function calls in 0.176 CPU seconds

---

Summary:

Flipping bits is tiny bit faster actually.To make negnums function produce the same result as flipbits, we need to change b=-i to b=-i-1 and this is even slower. Poke holes in my experiment please.

I don’t know the details of the compiler, but the negation operator on int objects also has a corresponding method: `__neg__`

-1 == (1).__neg__()

I was under the impression that Python will do constant folding when it compiles to bytecode. In that case, shouldn't "~0" be exactly as fast as "-1" at runtime?