Home > OS >  Can this array lookup be speeded up?
Can this array lookup be speeded up?

Time:07-10

I have a [64x64] table with only two values ( (1,-1), but if adopting other values, like (0,1) is convenient, they can be used)

The table looks like this:

table

The process to generate the table is complex, so I decided to memoize it, and convert into a 2D array

This code downloads this image, and converts into a numpy boolean table:

small table to post the data

import numpy as np
import matplotlib.pyplot as plt

URL="https://i.stack.imgur.com/q8CTy.png"

# Downloads the small image on this post in stackexchange
from io import BytesIO
from PIL import Image as PIL_Image
import requests

response = requests.get(URL)

#This is the table
table = ~np.array(PIL_Image.open(BytesIO(response.content)))

plt.imshow(table)
plt.show() 

I need to rapidly access the values of the table.

def function(r:int,c:int) -> int:
    return table[r][c]

That is the fastest way I can calculate the values, by looking into the table.

But I wonder if it can be done faster, maybe taking advantage of the fact that the table only has 2 values.

Because the table is 64x64, it can be compressed into 64x1 np.int64, but looking into an array of 64 bits and unpacking one bit, probably is as expensive as looking into a 64x64 array.

I wonder if there is a function that can look directly into the sequence of bits, since looking into 64x64 bits should be faster than in an array of 4096 values.

CodePudding user response:

You can access the elements of the array with table[r, c] which cuts down the time by roughly 40% on my machine.

CodePudding user response:

Assuming your calculations cannot take advantage of numpy vectorization, you can use enter image description here

  • Related