You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

82 lines
1.9 KiB

  1. # BEFORE CLIENT OPT:
  2. # Frames download time: 4.928671836853027
  3. # GIF creation time: 5.02190637588501
  4. # AFTER CLIENT OPT:
  5. # Frames download time: 3.885207176208496
  6. # GIF creation time: 4.356576204299927
  7. import os
  8. import socket
  9. import time
  10. import threading
  11. import multiprocessing
  12. from PIL import Image
  13. SERVER_URL = '127.0.0.1:1234'
  14. FILE_NAME = 'AmirlanSharipov.gif'
  15. CLIENT_BUFFER = 1024
  16. FRAME_COUNT = 5000
  17. MAXTHREADS = 8
  18. MAXPROCESSES = 8
  19. pool_sema = threading.BoundedSemaphore(value=MAXTHREADS)
  20. def routine_save_image(i):
  21. with pool_sema:
  22. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  23. ip, port = SERVER_URL.split(':')
  24. s.connect((ip, int(port)))
  25. image = b''
  26. while True:
  27. packet = s.recv(CLIENT_BUFFER)
  28. if not packet:
  29. break
  30. image += packet
  31. with open(f'frames/{i}.png', 'wb') as f:
  32. f.write(image)
  33. def download_frames():
  34. t0 = time.time()
  35. if not os.path.exists('frames'):
  36. os.mkdir('frames')
  37. threads = list()
  38. for i in range(FRAME_COUNT):
  39. t = threading.Thread(target=routine_save_image, args=(i, ))
  40. threads.append(t)
  41. for t in threads:
  42. t.start()
  43. for t in threads:
  44. t.join()
  45. return time.time() - t0
  46. def get_RGBA(fname):
  47. return Image.open(fname).convert('RGBA')
  48. def create_gif():
  49. t0 = time.time()
  50. frame_list = list()
  51. for frame_id in range(FRAME_COUNT):
  52. frame_list.append(f'frames/{frame_id}.png')
  53. with multiprocessing.Pool(MAXPROCESSES) as p:
  54. frames = p.map(get_RGBA, frame_list)
  55. frames[0].save(FILE_NAME, format="GIF",
  56. append_images=frames[1:], save_all=True, duration=500, loop=0)
  57. return time.time() - t0
  58. if __name__ == '__main__':
  59. print(f"Frames download time: {download_frames()}")
  60. print(f"GIF creation time: {create_gif()}")