当前位置:   article > 正文

Python多进程多线程测试_with threadpoolexecutor(max_workers=4) as executor

with threadpoolexecutor(max_workers=4) as executor:

今天在工作中遇到爬虫效率问题,在此处记录多进程、多线程测试脚本

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. __author__ = 'Seven'
  4. from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
  5. import time
  6. def gcd(pair):
  7. a, b = pair
  8. low = min(a, b)
  9. for i in range(low, 0, -1):
  10. if a % i == 0 and b % i == 0:
  11. return i
  12. numbers = [
  13. (1963309, 2265973), (1879675, 2493670), (2030677, 3814172),
  14. (1551645, 2229620), (1988912, 4736670), (2198964, 7876293)
  15. ]
  16. def thread_map_test():
  17. start_time = time.time()
  18. with ThreadPoolExecutor(max_workers=4) as pool:
  19. results = pool.map(gcd, numbers)
  20. results = list(results)
  21. end_time = time.time()
  22. print(f'运行结果:{results}')
  23. print(f'多线程map运行时长:{end_time - start_time}')
  24. def thread_submit_test():
  25. start_time = time.time()
  26. results = []
  27. with ThreadPoolExecutor(max_workers=4) as pool:
  28. for i in numbers:
  29. future = pool.submit(gcd, i)
  30. results.append(future)
  31. results = [result.result() for result in results]
  32. end_time = time.time()
  33. print(f'运行结果:{results}')
  34. print(f'多线程submit运行时长:{end_time - start_time}')
  35. def process_map_test():
  36. start_time = time.time()
  37. with ProcessPoolExecutor(max_workers=4) as pool:
  38. results = pool.map(gcd, numbers)
  39. results = list(results)
  40. end_time = time.time()
  41. print(f'运行结果:{results}')
  42. print(f'多进程map运行时长:{end_time - start_time}')
  43. def process_submit_test():
  44. start_time = time.time()
  45. results = []
  46. with ProcessPoolExecutor(max_workers=4) as pool:
  47. for i in numbers:
  48. future = pool.submit(gcd, i)
  49. results.append(future)
  50. results = [result.result() for result in results]
  51. end_time = time.time()
  52. print(f'运行结果:{results}')
  53. print(f'多进程submit运行时长:{end_time - start_time}')
  54. if __name__ == '__main__':
  55. thread_map_test()
  56. thread_submit_test()
  57. process_map_test()
  58. process_submit_test()

 

当多进程/多线程传参时,一个为可变变量,一个为不可变变量,可参照如下代码进行传参:

  1. with ProcessPoolExecutor(max_workers=4) as pool:
  2. pool.map(partial(data_crawl, variable_constant=variable_constant), variable_changed)

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/74894
推荐阅读
相关标签
  

闽ICP备14008679号