多线程的鸡肋 发表于 2019-07-12 | 分类于 python练习 123456789101112131415161718192021222324252627282930313233343536from contextlib import contextmanagerimport time## 因为GIL锁的原因,多线程并没有多少用## 不适合计算密集型@contextmanagerdef _cost_time(): start_time = time.time() print('start time : ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) yield end_time = time.time() seconds = end_time - start_time m, s = divmod(seconds, 60) h, m = divmod(m, 60) print('end time : ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) print('time cost %d:%02d:%02d ' % (h, m, s))def decrement(n): while n > 0: n -= 1# Single threadwith _cost_time(): decrement(100000000)#import threadingwith _cost_time(): t1 = threading.Thread(target=decrement,args=[50000000]) t2 = threading.Thread(target=decrement,args=[50000000]) t1.start() t2.start() t1.join() t2.join() 修改一下123456789101112131415161718192021222324252627282930313233343536import time## 因为GIL锁的原因,多线程并没有多少用## 不适合计算密集型def _cost_time(func): def warpper(*args,**kw): start_time = time.time() print('start time : ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) func(*args,**kw) end_time = time.time() seconds = end_time - start_time m, s = divmod(seconds, 60) h, m = divmod(m, 60) print('end time : ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) print('time cost %d:%02d:%02d ' % (h, m, s)) return warpper@_cost_timedef decrement(n): while n > 0: n -= 1# Single threaddecrement(100000000)# Multithreadingimport threadingt1 = threading.Thread(target=decrement,args=[50000000])t2 = threading.Thread(target=decrement,args=[50000000])t1.start()t2.start()t1.join()t2.join()