본문 바로가기

Python/고급

(18)
CPU Bound(2) - Multi-process CPU 연산 - 멀티 프로세스 from multiprocessing import current_process, Array, freeze_support, Process, Manager import time import os def cpu_bound(number, total_list): process_id = os.getpid() process_name = current_process().name # Process 정보 출력 print(f"Process ID: {process_id}, Process Name: {process_name}") total_list.append(sum(i * i for i in range(number))) def main(): numbers = [3_000_000 + x for x..
CPU Bound(1) - Single process CPU 연산 - 단일 프로세스 import time def cpu_bound(number): return sum(i * i for i in range(number)) def find_sums(numbers): result = [] for number in numbers: result.append(cpu_bound(number)) return result def main(): numbers = [3_000_000 + x for x in range(30)] # 확인 # print(numbers) start_time = time.time() total = find_sums(numbers) print() print(f"Total list : {total}") print(f"Sum : {sum(total)}") ..
[Python] I/O Bound(2) - Asyncio 통신관련 비동기 처리 import asyncio import aiohttp # import requests # 패키지는 동기방식이라서 사용불가. import time async def request_site(session, url): # 세션 확인 # print(session) # print(session.headers) async with session.get(url) as response: # status_code 동기화 문제 print("Read Contents {}, from {}, stauts:{}".format(response.content_length, url, response.status)) # print("*****Read Contents {0}, from {1}".format(respo..
[Python] I/O Bound(2) - Asyncio basic 비동기 기초 샘플 코드 동시 프로그래밍 패러다임 변화 싱글코어 -> 처리향상 미미, 저하 -> 비동기 프로그래밍 -> CPU연산, DB연동, API호출 대기 시간 늘어남 => 논블로킹으로 변환 파이썬에서 비동기 프로그래밍은 개념을 잘 잡아야 함. 파이썬 3.4에서 비동기(asyncio) 표준라이브러리 등장 import time import asyncio async def exe_calculate_async(name, n): for i in range(1, n + 1): print(f'{name} -> {i} of {n} is calculating..') # time.sleep(1) # 동기 처리, 시간비교하기 좋음 await asyncio.sleep(1) # 비동기 처리, 시간비교하기 좋음 print(f..
[Python] I/O Bound(2) - Multiproecessing 통신관련 멀티프로세스 처리(동기방식) import multiprocessing import requests import time # 각 프로세스 메모리 영역에 생성되는 객체(독립적) # 함수 실행 할 때 마다 객체 생성은 좋지 않음. -> 각 프로세스마다 할당 session = None def set_global_session(): global session if not session: session = requests.Session() print('>>> not session()') def request_site(url): # 세션 확인 print(session) # print(session.headers) with session.get(url) as response: name = multiproces..
[Python] I/O Bound(2) - Multithreading 통신관련 멀티스레드 처리(동기방식) import concurrent.futures import threading import requests import time # 각 스레드에 생성되는 객체(독립된 네임스페이스) thread_local = threading.local() # 세션 제공 def get_session(): if not hasattr(thread_local, "session"): # 딕셔너리 타입으로 확인 thread_local.session = requests.Session() print('>>> not hasattr()') return thread_local.session def request_site(url): # 세션 획득 session = get_session() # 세션 확인 pr..
[Python] I/O Bound(1) - Synchronous 통신관련 동기 처리 import requests import time def request_site(url, session): # checking session # print(session) # print(session.headers) with session.get(url) as response: print(f"[Read contents: {len(response.content)}, Status code: {response.status_code} from {url}") def request_all_site(urls): with requests.Session() as session: for url in urls: request_site(url, session) def main(): urls = [ "htt..
[Python] Blocking vs Non-Blocking, Sync vs Async Blocking vs Non-blocking Blocking - 시스템 콜 요청시 -> 커널 IO 작업 완료 시 까지 응답 대기 - 제어권(IO작업) -> 커널 소유 -> 응답(Response)전 까지 대기(Block) -> 다른 작업 수행 불가(대기) Non-blocking - 시스템 콜 요청시 -> 커널 IO 작업 완료 여부 상관없이 즉시 응답 - 제어권(IO작업) -> 유저 프로세스 전달 -> 다른 작업 수행 가능(지속) -> 주기적 시스템 콜 통해서 IO 작업 완료 여부 확인 Async vs Sync Sync : IO 작업 완료 여부에 대한 Noty는 유저프로세스(호출하는 함수) -> 커널(호출되는 함수) Async : IO 작업 완료 여부에 대한 Noty는 커널(호출되는 함수) -> 유저프로세스..