码迷,mamicode.com
首页 > 编程语言 > 详细

python,多线程应用示例

时间:2019-12-14 13:53:54      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:结果   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秒

python,多线程应用示例

标签:结果   day   star   程序运行时间   开启   color   %s   read   imp   

原文地址:https://www.cnblogs.com/iceberg710815/p/12038595.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!