# Multi Threading
import time
import threading as td
def calc(st, ed):
global global_list
tmp = 0
for i in range(st, ed):
tmp += i
global_list.append(tmp)
global_list = []
t1 = td.Thread(target=calc, args=(0, 25000000))
t2 = td.Thread(target=calc, args=(25000000, 50000000))
t3 = td.Thread(target=calc, args=(50000000, 75000000))
t4 = td.Thread(target=calc, args=(75000000, 100000000))
threads = [t1, t2, t3, t4]
time_start = time.time()
for t in threads:
t.start()
for t in threads:
t.join()
print (sum(global_list))
time_stop = time.time()
print ('Multi Threading: Time used: %.6f sec' % (time_stop - time_start))
4999999950000000
Multi Threading: Time used: 16.073000 sec
加了分开join的,运行时间反而比原来更长了。
其实,主要还是由于GIL锁的关系,系统同时处理的其实还是只是1个线程,只不过你同时启动多个,它就在多个线程里来回切换,这样反而增加了程序运行时间。 |