Advertisement
Guest User

Untitled

a guest
Apr 3rd, 2020
684
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.95 KB | None | 0 0
  1. import hashlib
  2. from io import DEFAULT_BUFFER_SIZE
  3.  
  4. def hash_md5_sha(file):
  5.     md5 = hashlib.md5()
  6.     sha = hashlib.sha1()
  7.     with open(file, mode='rb') as fl:
  8.         chunk = fl.read(DEFAULT_BUFFER_SIZE)
  9.         while chunk:
  10.             md5.update(chunk)
  11.             sha.update(chunk)
  12.             chunk = fl.read(DEFAULT_BUFFER_SIZE)
  13.     return md5.hexdigest(), sha.hexdigest()
  14.  
  15. def read_file(file):
  16.     with open(file, mode='rb') as fl:
  17.         chunk = fl.read(DEFAULT_BUFFER_SIZE)
  18.         while chunk:
  19.             chunk = fl.read(DEFAULT_BUFFER_SIZE)
  20.     return
  21.  
  22. files = ['sample{}'.format(i) for i in range(1, 41)] * 8
  23. from timeit import timeit
  24.  
  25. def time_single_core(func):
  26.         total = 0
  27.         for filename in files:
  28.                 total += timeit(stmt='{}(\'{}\')'.format(func, filename), globals=globals(), number = 1)
  29.         print ('Total using {}: {}'.format(func, total))
  30.  
  31. from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
  32.  
  33. time_single_core('read_file')
  34. time_single_core('hash_md5_sha')
  35.  
  36. def time_multi_thread(func):
  37.         def job(func):
  38.                 executor = ThreadPoolExecutor(4)
  39.                 executor.map(func, files)
  40.                 executor.shutdown()
  41.  
  42.  
  43.         globs = globals()
  44.         globs['job'] = job
  45.         total = timeit(stmt = "job({})".format(func), globals=globals(), number = 1)
  46.         print ('Total (multi-thread) using {}: {}'.format(func, total))
  47.  
  48. time_multi_thread('read_file')
  49. time_multi_thread('hash_md5_sha')
  50.  
  51. def time_multi_core(func):
  52.         def job(func):
  53.                 executor = ProcessPoolExecutor(4)
  54.                 executor.map(func, files)
  55.                 executor.shutdown()
  56.  
  57.         globs = globals()
  58.         globs['job'] = job
  59.         total = timeit(stmt = "job({})".format(func), globals=globs, number = 1)
  60.         print ('Total (multi-core) using {}: {}'.format(func, total))
  61.  
  62. time_multi_core('read_file')
  63. time_multi_core('hash_md5_sha')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement