in ,

Python Cache

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
    else:
        print("Not cached... calculating...")
        counter_num1 = []
        counter_num2 = []
        sum_list = []
        while int(num1) >=1:
            num1 = num1 / 2
            if num1 < 1: 
              pass             
            else:                 
               counter_num1.append(int(num1))         
            c = len(counter_num1)         
        while c > 0:
            num2 = num2 * 2
            counter_num2.append(num2)
            c -= 1
        for i in counter_num1:
            if int(i) % 2 == 1:
                cn1 = counter_num1.index(i)
                sum_list.append(counter_num2[cn1])
                z = sum(sum_list)
                CACHE[key] = z
        return z
 
def test_russian_perf():
    start_time = time.time()
    print(russian_alg(24,16))
    print("My Russian Peasant took: %f seconds to calculate" % (time.time()-start_time))
 
#This first call will not use cache
print(test_russian_perf())
#The next call will use cache as the calculation was already done and saved
print(test_russian_perf())

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…
384
My Russian Peasant took: 0.000045 seconds to calculate
384
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.)

What do you think?

0 points
Upvote Downvote

Total votes: 0

Upvotes: 0

Upvotes percentage: 0.000000%

Downvotes: 0

Downvotes percentage: 0.000000%

Written by Admin

I work for a Telecom company writing and testing software. My passion for writing code is expressed through this blog. It's my hope that it gives hope to any and all who are self-taught.

Comments

Leave a Reply

Loading…

Ruby Basics: Palindrome Test

R: Getting and Importing Data