Below is some code (also on my Github account) that makes use of cache to quickly respond to requests.

The actual calculation isn’t too useful. It’s an alternate way of performing multiplication.  What is useful however, is that the first time we call the function, it checks if it is in our dictionary called CACHE.  If it is, it pulls from there, bypassing the algorithm.   However, if it isn’t, it runs through the algorithm and then saves the result to CACHE.

import time
CACHE = {}

def russian_alg(num1, num2):
    key = (num1,num2) 
    if key in CACHE: 
        sum_list = CACHE[key] 
        return sum_list
        print("Not cached... calculating...")
        counter_num1 = []
        counter_num2 = []
        sum_list = []
        while int(num1) >=1:
            num1 = num1 / 2
            if num1 < 1: 
            c = len(counter_num1)         
        while c > 0:
            num2 = num2 * 2
            c -= 1
        for i in counter_num1:
            if int(i) % 2 == 1:
                cn1 = counter_num1.index(i)
                z = sum(sum_list)
                CACHE[key] = z
        return z

def test_russian_perf():
    start_time = time.time()
    print("My Russian Peasant took: %f seconds to calculate" % (time.time()-start_time))

#This first call will not use cache
#The next call will use cache as the calculation was already done and saved

I put a print in there, so that when I hit the non cache logic, that we can tell we are calculating the result.  When run I get this output:

Not cached… calculating…
My Russian Peasant took: 0.000045 seconds to calculate
My Russian Peasant took: 0.000006 seconds to calculate

384 is the result of the calculation.  The first time it was run, it wasn’t in cache.  So it prints out “Not cached, calculating” and runs the algorithm. The second time however, it finds it in cache and doesn’t print anything output the result immediately.  Notice the time difference.  It went from 0.000045 seconds to 0.000006 seconds (since the CACHE avoided running a calculation effort.)

Leave a Reply

Your email address will not be published. Required fields are marked *