[PYTHON] Bit operation of ring buffer (high speed)

Background

When using the ring buffer, the surplus was used to calculate the index. A programmer at work told me that I can do bit operations, so I'll write it down here.

Code(Python)

ring_buffer.py


# coding:utf-8
'''
Experiment whether Ring Buffer becomes faster by bit operation
'''
import time
import numpy as np

def main():
    ring_buff = np.array([i for i in range(1024)])

    #Modulo operation ver
    start = time.time()

    for cnt in range(102400):
        index = cnt % 1024
        ring_buff[index] = cnt

    elapsed_time = time.time() - start
    print ("Surplus ver:{0}".format(elapsed_time) + "[sec]")    
    
    #bit operation ver
    start = time.time()

    for cnt in range(102400):
        index = cnt & 0b1000000000
        ring_buff[index] = cnt

    elapsed_time = time.time() - start
    print ("bit ver   :{0}".format(elapsed_time) + "[sec]")

if __name__ == '__main__':
    main()


Recommended Posts

Bit operation of ring buffer (high speed)
Bit operation
Logical operation / bit operation 0
[Python] Operation of enumerate
Basic operation of pandas
Basic operation of Pandas