以下代码结果可看到python的多线程执行时间比单线程还慢,是因为GIL全局锁影响了python的执行效率,具体可参考:https://blog.csdn.net/qq_39338671/article/details/87457812
#! /usr/bin/python
#-*- coding:UTF-8 -*-
from threading import Thread,current_thread
import time
def decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
func()
end_time = time.time()
print("total time:{}".format(end_time - start_time))
return wrapper
def my_count():
j=0
for i in range(0,2):
print("start %s %s\n" % (current_thread().name,time.time()))
for j in range(1000000):
j=j+1
print("end %s %s\n" % (current_thread().name,time.time()))
return True
#线程串行
@decorator
def main1():
thread_array={}
for tid in range(2):
t=Thread(target=my_count)
t.start()
t.join()
#线程并发
@decorator
def main2():
thread_array={}
for tid in range(2):
t=Thread(target=my_count)
t.start()
thread_array[tid]=t
for i in range(2):
thread_array[i].join()
if __name__=='__main__':
main1()
main2()
结果:
#串行结果
start Thread-1 1587531413.27
end Thread-1 1587531413.35
start Thread-1 1587531413.35
end Thread-1 1587531413.4
start Thread-2 1587531413.4
end Thread-2 1587531413.45
start Thread-2 1587531413.45
end Thread-2 1587531413.49
total time:0.223469018936
#并发结果
start Thread-3 1587531413.49
start Thread-4 1587531413.5
end Thread-3 1587531413.63
start Thread-3 1587531413.64
end Thread-4 1587531413.64
start Thread-4 1587531413.65
end Thread-3 1587531413.74
end Thread-4 1587531413.74
total time:0.252161979675
网友评论