Advertisement
mmandrille

Untitled

Aug 30th, 2022 (edited)
740
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.88 KB | None | 0 0
  1. #Python import
  2. import time
  3. from datetime import datetime
  4.  
  5. # Functions
  6. # Python imports
  7. import time
  8. import string
  9. import hashlib
  10. #Package import
  11. from pymemcache import serde
  12. from pymemcache.client import base as base_memcache
  13.  
  14. # Constants:
  15. zconsts_TIMES = 100
  16. zconsts_FAKE_DELAY = 5
  17.  
  18. # Functions definition
  19. def fetch_from_db(key):
  20.     # In this function we will simulate a slow database query
  21.     time.sleep(zconsts_FAKE_DELAY)
  22.     # Return hashed key
  23.     return str(hashlib.md5(key.encode("utf-8")))
  24.  
  25. def get_cache_client():
  26.     return base_memcache.Client("10.82.1.3:11211", serde=serde.pickle_serde)
  27.  
  28. def get_cached_object(CacheClient, key):
  29.     message = CacheClient.get(key, None)
  30.     if not message:
  31.         # we dont have it on cache, we will have to look for it to Database:
  32.         message = fetch_from_db(key)
  33.         # After fetching we store it on cache:
  34.         CacheClient.set(key, message)
  35.     # At this point we have the message
  36.     return message
  37.  
  38. #Launch!
  39. if __name__ == "__main__":
  40.     key = "Testing"
  41.     # Instance MemCache client for every cert_sender process
  42.     CacheClient = get_cache_client() # This could be in a lot of places of a project
  43.     CacheClient.delete(key) # To avoid already existing key
  44.     # Run testing
  45.     performance = {}
  46.     for x in range(zconsts_TIMES):
  47.         check_time = datetime.now()
  48.         get_cached_object(CacheClient, key) # We fetch our item
  49.         performance[x] = (datetime.now() - check_time).total_seconds()
  50.        
  51.     # Show some results
  52.     print("Results:")
  53.     print(f"First time took {performance[0]:.4f}s fetching from database")
  54.     print("At this point we set the key on Cache to retrieve value from there\n")
  55.     print(f"All the next {zconsts_TIMES-1} fetchs should be faster")
  56.     for idx in range(1, zconsts_TIMES):
  57.         print(f"{idx} time\t Took {performance[idx]:.4f}s fetching from Cache")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement