스레딩 Threading

single Thread

Multi Thread

# 스레드 Thread
 import time
 def doing() :
     time.sleep( 1 )
     print( "실행중" )

 start = time.time()
 for i in range( 10 ) :
     doing()
 end = time.time()
 print( "실행시간 :", (end-start) )        

import time
import threading
 def doing() :
     time.sleep( 1 )
     print( "스레드 실행중" )
 if __name__ == "__main__" :
     start = time.time()
     threads = []
     for i in range( 10 ) :
         t = threading.Thread( target=doing )
         t.start()       # 실행대기 상태
         threads.append( t )
     for thread in threads :
         thread.join()
     end = time.time()
     print( "실행시간 :", (end-start) )

cuncurrent 모듈 이용

from concurrent import futures              # start() join()을 자동으로 처리
 def doing() :
     time.sleep( 1 )
     return "스레드 실행중"
 if __name__ == "__main__" :
     start = time.time()
     results = []
     with futures.ThreadPoolExecutor() as excutor :
         for i in range( 10 ) :
             result = excutor.submit( doing )
             results.append( result )
     for f in futures.as_completed( results ) :
         print( f.result() )
     end = time.time()
     print( "실행시간 :", (end-start) )

 def calc_sum( list ) :
     sum = 0
     for i in range( list[0], list[1]+1 ) :
         sum += i
     return sum
 if __name__ == "__main__" :
     start = time.perf_counter()
     result = calc_sum( [1, 100000000] )
     print( result )
     end = time.perf_counter()
     print( "실행시간 :", (end-start) )

 def calc_sum( list ) :
     sum = 0
     for i in range( list[0], list[1]+1 ) :
         sum += i
     return sum
 if __name__ == "__main__" :
     start = time.time()
     with futures.ThreadPoolExecutor() as excutor :
         sub = [ [1, 100000000//2], [100000000//2 +1, 100000000] ]
         results = excutor.map( calc_sum, sub )
     print( sum( results ) )
     end = time.time()
     print( "실행시간 :", (end-start) )

멀티 프로세스

# 멀티 프로세스
from multiprocessing import Pool
 def calc_sum(list):
     sum = 0
     for i in range(list[0], list[1]+1):
         sum+=i
     print(sum)
 if __name__ == "__main__" :
     start = time.time()
     sub = [ [1, 100000000//2], [100000000//2 +1, 100000000] ]
     pool = Pool(processes=2)
     pool.map(calc_sum, sub)
     pool.close()
     pool.join()
     end = time.time()
     print("실행시간 :", (end-start))