python,多线程应用示例

应用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)
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:0.0003719329833984375

Process finished with exit code 0
程序用了不到1秒

猜你喜欢

转载自www.cnblogs.com/iceberg710815/p/12038595.html