병렬프로그래밍을 이론으로만 배우지말고 실전에 적용시켜보고 싶어졌는데, 어디쓰면 좋을까 생각해보다가 스크립트 짜 놓은게 생각남
찾아보니 python은 멀티프로세싱이라는 내부 모듈을 지원
multiprocessing - Process-based parallelism - Python 3.10.7 documentation
프로세스의 수가 크다고 무조건 성능이 좋은게 아님(cpu bound나 context switching overhead)
Are there any guidelines to follow when choosing number of processes with multiprocessing?
Does the M1 chip (Apple Silicon) use hyper-threading? (a.k.a. simultaneous multithreading (SMT))
병렬 프로그래밍 적용 코드
import json
import multiprocessing as mp
import time
import pandas as pd
def scrap_problems(chapter):
url = f'<https://github.com/encrypted-def/basic-algo-lecture/blob/master/workbook/{chapter}.md>'
try:
workbook = {}
table = pd.read_html(url)
problems = [ problem for problem in table[0]["문제"]]
workbook[f"{chapter}"] = problems
return workbook
except Exception as e:
print('예외 발생 사유: ', e)
if __name__=='__main__':
start_time = time.time()
chapters = ["0x{:02X}".format(i) for i in range(2, 32)]
pool = mp.Pool(processes=mp.cpu_count())
chapter_problems = pool.map(scrap_problems, chapters)
# pool이 작업을 끝낸 뒤에 join과 close를 불러줘야되는 이유
# <https://stackoverflow.com/questions/38271547/when-should-we-call-multiprocessing-pool-join>
pool.close()
pool.join()
print("--- %s seconds ---" % (time.time() - start_time))
workbook = { next(iter(chapter_problem)): list(*chapter_problem.values()) for chapter_problem in chapter_problems if not chapter_problem is None }
with open('workbook.json', 'w', encoding='utf-8') as file:
json.dump(workbook, file)
병렬 프로그래밍 미적용 코드
import pandas as pd
import json
import time
chapters = ["0x{:02X}".format(i) for i in range(2, 32)]
workbook = {}
start_time = time.time()
for chapter in chapters:
url = f'<https://github.com/encrypted-def/basic-algo-lecture/blob/master/workbook/{chapter}.md>'
try:
table = pd.read_html(url)
problems = [ problem for problem in table[0]["문제"]]
workbook[f"{chapter}"] = problems
except Exception as e:
print('예외 발생 사유: ', e)
print("--- %s seconds ---" % (time.time() - start_time))
with open('workbook.json', 'w', encoding='utf-8') as file:
json.dump(workbook, file)
multi thread로 스크래핑 할 때
로컬에서는 13초나 차이가 난다
git actions에서 쓰는 컴터는 얼마나 빨라질까? 모니터링 해보니 기존에 13초 걸리던 작업이 3초로 줄었다 획기적이다!
thread, multicore, parallel programming
multicore scheduling
쓰레드는 스케줄러의 단위
쓰레드는 코어에 종속(PCB를 공유할 수는 있지만 쪼갤 수 없음)
쓰레드를 쓰면 성능이 올라가는 이유는 멀티코어를 이용할 수 있는 환경에서 만약 싱글 쓰레드로 돌린다면 하나의 코어밖에 이용못하고 다른 코어는 놀지만, 여러개의 쓰레드로 동시에 처리한다면 멀티 코어를 활용할 수 있어서 성능이 올라감, 그리고 하나가 처리할 양보다 나눠서 처리하니 각각이 처리할 양이 줄어듦
학부 때 어드밴스드 토픽이라 대강만 알고 넘어갔는데, 실제로 쓰레드가 어떻게 구현되는것이고, 왜 성능향상을 이끌어낼 수 있는지에 대해 궁금해서 검색해보다가 잘 설명해놓은 링크를 발견했음
scheduler
리눅스에서 사용한다는 CFS 스케줄링이 뭔지 대강만 알고있었는데 발견한 링크에서 이를 설명한 글이 있길래 남겨놓는다