Created
June 17, 2022 03:34
-
-
Save KnightChaser/11a48d3a9ade9e99c496167ca312778d to your computer and use it in GitHub Desktop.
일일이 주사위를 던지는 건 귀찮지 않나요? 파이썬을 시켜서 주사위를 던져봅시다. 더 효과적으로 CPU에게 일을 하도록 시키기 위해, 멀티프로세싱을 사용해 보자구요!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import time | |
import os | |
from multiprocessing import Process, Queue | |
def roll_the_dice(id, start, end, result): | |
counters = [0, 0, 0, 0, 0, 0] | |
for _seq in range(start, end): | |
value = random.randint(0, 5) | |
counters[value] = counters[value] + 1 | |
result.put(counters) | |
def print_result(count, dataset, start_time, finish_time): | |
dice_number = 1 | |
print("~~ Python with Multiprocessing ~~") | |
print(f"** << 주사위 던지기 시뮬레이션 결과 ({format(count, ',')} 번 실행) >> **\n") | |
for _seq in range(0, len(dataset)): | |
dice_hit_qty = dataset[_seq] | |
dice_hit_ratio = round((dice_hit_qty / count) * 100, 3) | |
print(f"[{dice_number}]번은 {format(dice_hit_qty,','):>10s}번({dice_hit_ratio}%) 나왔습니다.") | |
dice_number += 1 | |
print(f"작동 시간 {round(finish_time - start_time, 4)} 초") | |
if __name__ == "__main__": | |
start_time = time.time() | |
COUNT = 1000000 | |
multiprocess_qty = 6 | |
processPool = [] | |
result = Queue() | |
for _seq in range(0, multiprocess_qty): | |
process = Process(target=roll_the_dice, args=(_seq, 1, COUNT, result)) | |
processPool.append(process) | |
process.start() | |
for process in processPool: | |
process.join() | |
result.put('STOP') | |
total_counters = [0, 0, 0, 0, 0, 0] | |
while True: | |
temp = result.get() | |
if temp == 'STOP': | |
break | |
else: | |
for _seq in range(0, len(total_counters)): | |
total_counters[_seq] += temp[_seq] | |
finish_time = time.time() | |
print_result(COUNT * multiprocess_qty, total_counters, start_time, finish_time) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment