from threading import Thread
import time
start_time = time.time()
def work(id, start, end, result):
total = 0
for i in range(start, end):
total += i
result.append(total)
return
if __name__ == "__main__":
START, END = 0, 100000000
result = list()
th1 = Thread(target=work, args=(1, START, END, result))
th1.start()
th1.join()
print("--- time %s seconds ---" % (time.time() - start_time))
print(f"Result: {sum(result)}")
# --- time 4.46619987487793 seconds ---
# Result: 4999999950000000
from threading import Thread
import time
start_time = time.time()
def work(id, start, end, result):
total = 0
for i in range(start, end):
total += i
result.append(total)
return
if __name__ == "__main__":
START, END = 0, 100000000
result = list()
th1 = Thread(target=work, args=(1, START, END//2, result))
th2 = Thread(target=work, args=(2, END//2, END, result))
th1.start()
th2.start()
th1.join()
th2.join()
print("--- time %s seconds ---" % (time.time() - start_time))
print(f"Result: {sum(result)}")
# --- time 4.254441976547241 seconds ---
# Result: 4999999950000000
import time
start_time = time.time()
total = 0
for i in range(0, 100000000):
total += i
print("--- time %s seconds ---" % (time.time() - start_time))
print(f"Result: {total}")
# print(total)
# --- time 8.859218835830688 seconds ---
# Result: 4999999950000000
thread 1개 | thread 2개 | multithread X |
---|---|---|
4.46619987487793 seconds | 4.254441976547241 seconds | 8.859218835830688 seconds |
if __name__ == "__main__": START, END = 0, 100000000 result = list() th1 = Thread(target=work, args=(1, START, END, result)) th1.start() th1.join()
*if name == 'main': 안에서 실행해야 함.
thread 객체 생성
Thread(target=work, args=(arg, [[[args], args], ...])
parameter | Description |
---|---|
target | 스레드가 실행할 함수 |
args | 함수의 인자들 |
thread 시작
th1.start()
thread 실행이 완료될 때까지 기다림
th1.join()