멀티프로세싱 활용
이제 멀티프로세싱 (multiprocessing) 을 사용하여 계산 속도를 높여 보겠습니다. Python 의 멀티프로세싱은 여러 프로세스를 실행할 수 있게 해주며, 이는 서로 다른 CPU 코어에서 실행될 수 있어 CPU 바운드 (CPU-bound) 작업에 필요한 총 시간을 줄여줍니다.
~/project 디렉토리에 process_prime.py라는 파일을 열고 다음 내용을 입력하세요.
from multiprocessing import Process
import math
def is_prime(num):
"""
Check if a number is prime.
"""
if num <= 1:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
def compute_primes(start, end):
"""
Compute prime numbers within a given range.
"""
prime_numbers = [num for num in range(start, end) if is_prime(num)]
print(f"Primes in range {start}-{end}: {prime_numbers}")
processes = []
## Creating two processes
for i in range(0, 20000, 10000):
## Create a new process targeting the compute_primes function and passing the range as arguments
p = Process(target=compute_primes, args=(i, i+10000))
processes.append(p)
## Start the process
p.start()
## Wait for all processes to finish
for p in processes:
p.join()
print("Done with prime computation!")
터미널에서 스크립트를 실행합니다.
python process_prime.py
그러면 지정된 범위에서 발견된 소수가 출력되고 완료 메시지가 표시됩니다.
Primes in range 0-10000: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241,
... ...
9851, 9857, 9859, 9871, 9883, 9887, 9901, 9907, 9923, 9929, 9931, 9941, 9949, 9967, 9973]
Primes in range 10000-20000: [10007, 10009, 10037, 10039, 10061, 10067, 10069, 10079, 10091, 10093, 10099, 10103, 10111, 10133, 10139, 10141, 10151, 10159, 10163, 10169, 10177, 10181, 10193,
... ...
19739, 19751, 19753, 19759, 19763, 19777, 19793, 19801, 19813, 19819, 19841, 19843, 19853, 19861, 19867, 19889, 19891, 19913, 19919, 19927, 19937, 19949, 19961, 19963, 19973, 19979, 19991, 19993, 19997]
Done with prime computation!