본문 바로가기
CS/Interview

[Python] 병렬처리(Multiprocessing)를 통한 연산속도 개선

by Shark_상어 2023. 2. 18.
728x90

파이썬 multiprocessing라이브러리의 Pool Process를 활용하여 병렬구조로 연산을 처리할 수 있다.

 

 

일반적 연산

def work_func(x):
    print("value %s is in PID : %s" % (x, os.getpid()))
    time.sleep(1)
    return x ** 5

def main():
    start = int(time.time())
    print(list(map(work_func, range(0, 12))))
    print("***run time(sec) :", int(time.time()) - start)

if __name__ == "__main__":
    main()

# 결과를 보면 1개의 피드(PID : 15848)가 작업을 처리하고, 1초간 멈추라고 했으므로 작업 수행까지 12초가 걸린 것을 확인 할 수 있다.

병렬처리 Pool

 

import time, os
from multiprocessing import Pool

def work_func(x):
    print("value %s is in PID : %s" % (x, os.getpid()))
    time.sleep(1)
    return x ** 5

def main():
    start = int(time.time())
    num_cores = 6
    pool = Pool(num_cores)
    print(pool.map(work_func, range(1, 13)))
    print("***run time(sec) :", int(time.time()) - start)

if __name__ == "__main__":
    main()

Pool안의 값으로 job을 할당받을 Process의 수를 의미한다.

 

위와 같이 6개의 Process에 할당하고 동일하게 map함수를 전달해본 결과,

 

6개의 피드(PID : 20432, 20448, 20472, 19500, 13888, 8056)가 12개의 수를 2개씩 할당받아 작업을 수행했고 수행시간도

 

2초로 감소 했음을 알수 있다.

 

다음은 프로세스 관련하여 실험 해보고자 한다.

728x90

'CS > Interview' 카테고리의 다른 글

쿠버네티스 란 무엇인가??  (0) 2023.03.07
Redis는 무엇인가??  (0) 2023.02.19
[Python] 'is'와 '=='의 차이  (0) 2023.02.16
Python String concat 시간 복잡도  (0) 2023.02.16
불변형 자료형과 변형 자료형  (0) 2023.02.16