프로그래밍/Python

[Python] Python 멀티프로세싱 예제 with concurrent.futures

엔지니어- 2021. 7. 31. 16:10
반응형

Python에서 멀티프로세싱을 구현한 예제입니다.

  • 사용 모듈 : concurrent.futures
  • 테스팅 알고리즘 : 소수(Prime number) 판별 ← 에라토스테네스의체 X, 테스트를 위해 계산 집약적인 알고리즘 사용
  • 112272535095293과 같은 15자리 소수 8개 사용

 

테스트 케이스 3가지 결과 

  • Single Process : 4.03초
  • Multi Thread (4) : 4.15초 / 문서 하단에 참고자료로 정리한 '불곰'님 블로그를 보면 Python에서 멀티프로세싱을 구현하려면 Multi Thread가 아닌 Multi Process를 사용해야 한다고 합니다. Single Process보다 느렸던 이유는 오버헤드 때문인 것 같습니다. 
  • Multi Process (4) : 1.90초

테스트 결과

 

상세한 설명보다는 아래에 실행해볼 수 있는 예제 코드와 참고자료 링크 남기겠습니다.

 

예제 코드

.py 파일로 저장 후 실행해보실 수 있습니다.

import concurrent.futures
import math
import time

PRIMES = [
    112272535095293,
    112582705942171,
    112272535095293,
    115280095190773,
    115797848077099,
    112272535095293,
    112582705942171,
    112272535095293
#     115280095190773,
#     115797848077099,
]

def is_prime(n):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def case_single_process():
    strt_time = time.time()
    for x in PRIMES:
        print("%d is prime: %s" % (x, is_prime(x)))
        
    print("# Single Process / Time differnce:", round(time.time() - strt_time, 2), 'Seconds')


def case_multi_thread():
    strt_time = time.time()
    executor = concurrent.futures.ThreadPoolExecutor(max_workers=4)
    for number, x in zip(PRIMES, executor.map(is_prime, PRIMES)):
        print("%d is prime: %s" % (number, x))

    print("# Multi Thread / Time differnce : ", round(time.time() - strt_time, 2), 'Seconds')


def case_multi_process():
    strt_time = time.time()
    executor = concurrent.futures.ProcessPoolExecutor(max_workers=4)
    for number, x in zip(PRIMES, executor.map(is_prime, PRIMES)):
        print("%d is prime: %s" % (number, x))
        
    return print("# Multi Process / Time differnce : ", round(time.time() - strt_time, 2), 'Seconds')


if __name__ == '__main__':
    
    case_single_process()
    case_multi_thread()
    case_multi_process()

# 참고자료
# 불곰님 블로그, [Python 진정한 병렬성을 ...] https://brownbears.tistory.com/238
# 하나씩 점을 찍어 나가며님 블로그, [Python 멀티 프로세싱은 parmap으로하자], https://dailyheumsi.tistory.com/105
# Python 공식문서, [concurrent.futures] , https://docs.python.org/3/library/concurrent.futures.html

 

기타 궁금하신 사항은 댓글 남겨주세요.

 

감사합니다.

 

참고자료

1. 불곰님 블로그, [Python 진정한 병렬성을 ...] https://brownbears.tistory.com/238
2. 하나씩 점을 찍어 나가며님 블로그, [Python 멀티 프로세싱은 parmap으로하자], https://dailyheumsi.tistory.com/105
3. Python 공식문서, [concurrent.futures] , https://docs.python.org/3/library/concurrent.futures.html
반응형