标签:结果 day star 程序运行时间 开启 color %s read imp
应用python的threading模块开启多线程执行程序,会缩短程序运行时间,下面代码演示了多线程应用
#不开启多线程演示 import time,threading def foo(n): print(‘foo%s‘%n) time.sleep(1) def bar(n): print(‘bar%s‘%n) time.sleep(2) begin = time.time() t1 = threading.Thread(target = foo,args = (1,)) t2 = threading.Thread(target = bar,args = (2,)) #t1.start() #t2.start() foo(1) bar(2) end = time.time() process_time = end - begin print(‘process time is:%s‘%(str(process_time)))
上面不开启多线程的情况下执行结果如下:
/usr/bin/python3.6 /home/guoming/python/day27/thread.py
foo1
bar2
process time is:3.003460168838501
Process finished with exit code 0
程序运行花了3秒时间
#改写一下,开启两个线程
import time,threading
def foo(n):
print(‘foo%s‘%n)
time.sleep(1)
def bar(n):
print(‘bar%s‘%n)
time.sleep(2)
begin = time.time()
t1 = threading.Thread(target = foo,args = (1,))
t2 = threading.Thread(target = bar,args = (2,))
t1.start()
t2.start()
#foo(1)
#bar(2)
print(‘......main.........‘)
t1.join()
t2.join()
end = time.time()
process_time = end - begin
print(‘process time is:%s‘%(str(process_time)))
开启线程后执行结果如下:
/usr/bin/python3.6 /home/guoming/python/day27/thread.py
foo1
bar2
......main.........
process time is:2.0026726722717285
Process finished with exit code 0
程序用了2秒
标签:结果 day star 程序运行时间 开启 color %s read imp
原文地址:https://www.cnblogs.com/iceberg710815/p/12038595.html