Python의 멀티스레딩 및 멀티프로세싱 초보자 가이드 - 1부

백엔드 엔지니어 또는 데이터 과학자로서 올바른 데이터 구조와 알고리즘을 사용했다고 가정하고 프로그램 속도를 개선해야 하는 경우가 있습니다. 이를 수행하는 한 가지 방법은 다중 스레딩 또는 다중 처리 사용의 이점을 활용하는 것입니다.
이 게시물에서는 다중 스레딩 또는 다중 처리의 내부 작업에 대해 자세히 설명하지 않습니다. 대신 Unsplash에서 이미지를 다운로드하는 작은 Python 스크립트를 작성합니다. 이미지를 동기식으로 또는 한 번에 하나씩 다운로드하는 버전부터 시작하겠습니다. 다음으로 스레딩을 사용하여 실행 속도를 향상시킵니다.

나는 당신이 이것을 배우게되어 기쁩니다 ...

멀티스레딩



간단히 말해서 스레딩을 사용하면 프로그램을 동시에 실행할 수 있습니다. 외부 이벤트를 기다리는 데 많은 시간을 소비하는 작업은 일반적으로 스레딩에 적합합니다. I/O 바운드 작업(예: 파일 쓰기 또는 읽기, 네트워크 작업 또는 API를 사용하여 온라인에서 항목 다운로드)이라고도 합니다.
스레드 사용의 이점을 보여주는 예를 살펴보겠습니다.

스레딩 없이
이 예제에서는 프로그램을 순차적으로 실행하여 Unsplash API에서 15개의 이미지를 다운로드하는 데 걸리는 시간을 확인하려고 합니다.

import requests
import time
img_urls = [
    'https://images.unsplash.com/photo-1516117172878-fd2c41f4a759',
    'https://images.unsplash.com/photo-1532009324734-20a7a5813719',
    'https://images.unsplash.com/photo-1524429656589-6633a470097c',
    'https://images.unsplash.com/photo-1530224264768-7ff8c1789d79',
    'https://images.unsplash.com/photo-1564135624576-c5c88640f235',
    'https://images.unsplash.com/photo-1541698444083-023c97d3f4b6',
    'https://images.unsplash.com/photo-1522364723953-452d3431c267',
    'https://images.unsplash.com/photo-1513938709626-033611b8cc03',
    'https://images.unsplash.com/photo-1507143550189-fed454f93097',
    'https://images.unsplash.com/photo-1493976040374-85c8e12f0c0e',
    'https://images.unsplash.com/photo-1504198453319-5ce911bafcde',
    'https://images.unsplash.com/photo-1530122037265-a5f1f91d3b99',
    'https://images.unsplash.com/photo-1516972810927-80185027ca84',
    'https://images.unsplash.com/photo-1550439062-609e1531270e',
    'https://images.unsplash.com/photo-1549692520-acc6669e2f0c'
]

start = time.perf_counter() #start timer
for img_url in img_urls:
    img_name = img_url.split('/')[3] #get image name from url
    img_bytes = requests.get(img_url).content
with open(img_name, 'wb') as img_file:
     img_file.write(img_bytes) #save image to disk 

finish = time.perf_counter() #end timer
print(f"Finished in {round(finish-start,2)} seconds") 

#results
Finished in 23.101926751 seconds


스레딩 포함
Pyhton의 스레딩 모듈이 프로그램 실행을 크게 향상시키는 방법을 살펴보겠습니다.

import time
from concurrent.futures import ThreadPoolExecutor

def download_images(url):
    img_name = img_url.split('/')[3]
    img_bytes = requests.get(img_url).content
    with open(img_name, 'wb') as img_file:
         img_file.write(img_bytes)
         print(f"{img_name} was downloaded")

start = time.perf_counter() #start timer
with ThreadPoolExecutor() as executor:
    results = executor.map(download_images,img_urls) #this is Similar to map(func, *iterables)
finish = time.perf_counter() #end timer
print(f"Finished in {round(finish-start,2)} seconds")

#results 
Finished in 5.544147536 seconds


Python에서 스레딩 모듈을 사용하는 방법을 더 잘 이해하려면 다음 링크를 방문하십시오. https://docs.python.org/3/library/concurrent.futures.html

코드를 스레딩하지 않은 경우에 비해 스레딩 코드 속도가 크게 향상되었습니다. 즉, 23초에서 5초로 💃.
이 예의 경우 스레드를 생성하는 데 오버헤드가 있으므로 단일 호출이 아닌 여러 API 호출에 스레드를 사용하는 것이 좋습니다.

또한 데이터 크런칭과 같은 집중적인 계산의 경우 이미지 조작 멀티프로세싱이 스레드보다 성능이 좋습니다.

결론적으로 I/O 바운드 작업의 경우 프로그램이 동기적으로 실행될 때마다 실제로 CPU에서 많은 작업을 수행하지 않습니다. 아마도 입력을 기다리고 있을 것입니다. 이는 실제로 멀티스레딩을 사용하여 프로그램을 동시에 실행하면 몇 가지 이점을 얻을 수 있다는 좋은 신호입니다.

다음 주 2부에서는 CPU 사용량이 많은 작업에 다중 처리를 사용하여 프로그램 속도를 높이는 방법을 배웁니다 :).
다음으로, Django 애플리케이션을 로컬 컴퓨터에서 실행 중인 Docker화된 PostgreSQL 및 pgAdmin 4 이미지에 연결하는 방법을 배웁니다😎

저를 팔로우하고 알림을 켜주세요. 고맙습니다!
즐거운 코딩하세요! ✌

좋은 웹페이지 즐겨찾기