3

Suppose I have two bitboards represented using a numpy array:

import numpy

bitboard = numpy.zeros(2, dtype=numpy.int64)

Let's say that I want to set the 10th bit of the first bitboard. What's the fastest way to do this?


There are two ways that I can think of. Here's the first way:

numpy.bitwise_or(a[0], numpy.left_shift(1, 10), out=a, where=(True, False))

Here's the second way:

a[0] |= 1 << 10

Which one is faster? Is there any other way to do this? In particular, I'd like to know:

  1. When I access a[0] does numpy return an int64 or a Python long?
  2. If it returns a Python long then I'm assuming that both methods are pretty slow because they work on arbitrary-precision numbers. Am I right in assuming that?
  3. If so then is there any way to get bitwise operations to work on fixed-precision numbers?

Note that I'm using Python version 3.

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299

1 Answers1

2

Which one is faster? Is there any other way to do this?

The second method is faster.

When I access a[0] does numpy return an int64 or a Python long?

It'll return an int64.

If it returns a Python long then I'm assuming that both methods are pretty slow because they work on arbitrary-precision numbers. Am I right in assuming that?

More details in this thread: Slow bitwise operations

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
ShreyasG
  • 766
  • 4
  • 11
  • Thanks for cleaning up my answer :) – ShreyasG Oct 11 '17 at 04:58
  • 3
    "The second method is faster." <-- proof? Also, not seeing an answer to the original question in the link you provided. – charlesreid1 Oct 11 '17 at 04:59
  • Using timeit, _CPU times: user 34 µs, sys: 0 ns, total: 34 µs_ for the first and _CPU times: user 8 µs, sys: 1 µs, total: 9 µs_ for the second method. The question was an open ended and I have attempted to answer some of those. – ShreyasG Oct 11 '17 at 05:22