Check Speed of Bitwise FizzBuzz

Use Jupyter notebook magic timeit to see the differences in time of various expressions.

I created a post on how to solve the FizzBuzz challenge using bitwise operators.

In [24]:
x, y = 3, 5
xy = 3 * 5
words = FIZZ, BUZZ = "Fizz", "Buzz"
FIZZBUZZ = ''.join(words)
In [25]:
def FizzBuzz(i):
    if i % xy == 0:
        return FIZZBUZZ
    elif i % x == 0:
        return FIZZ
    elif i % y == 0:
        return BUZZ
    else:
        return i

Measure time with a function call.

In [4]:
%%timeit
[FizzBuzz(i) for i in range(1, 101)]
71.1 µs ± 3.42 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Measure time without a function call.

In [22]:
%%timeit
for i in range(1, 101):
    if i % xy == 0:
        FIZZBUZZ
    elif i % x == 0:
        FIZZ
    elif i % y == 0:
        BUZZ
    else:
        i
42.7 µs ± 3.1 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [16]:
choices = [[i, FIZZ, BUZZ, FIZZBUZZ] for i in range(1, 101)]
In [17]:
%%timeit
[choices[i][0x30490610>>i%15*2&3] for i in range(100)]
84 µs ± 3.44 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [18]:
choices = dict(zip(range(1, 4), (FIZZ, BUZZ, FIZZBUZZ)))
In [19]:
%%timeit

[choices.get(0x30490610>>i%15*2&3, i) for i in range(100)]
90.7 µs ± 3.51 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [20]:
%%timeit

[0x30490610>>i%15*2&3 for i in range(100)]
67.5 µs ± 4.96 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [23]:
%%timeit

for i in range (100):
    0x30490610>>i%15*2&3
56.8 µs ± 3.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)