python的单线程与多线程时间比较

test1.py...执行完时间3秒钟 (用多线程)

#test1.py

import time
import threading


def sing(a):
	print ('sing get arg is %s' %a)
	for x in range(0,3):		
		print 'sing fun '
		time.sleep(1)

def dance(a):
	print ('dance get arg is %s' %a)
	for x in range(0,3):		
		print 'dance fun '
		time.sleep(1)
		
def main():
	a='jack'
	
	#sing thread
	tsing=threading.Thread(target=sing,name='singing',args=(a,))
	#dance thread
	tdance=threading.Thread(target=dance,name='danceing',args=(a,))
	
	#start thread
	t=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
	print ('start time is %s' %t)
	tsing.start()
	tdance.start()
	
	tsing.join()
	tdance.join()
	
	print('this is master thread...')
	e=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
	print ('start time is %s' %e)
	

if __name__=="__main__":
	main()
	

test2.py,执行完是6秒钟 (单线程)

#test2.py

import time
import threading


def sing(a):
	print ('sing get arg is %s' %a)
	for x in range(0,3):		
		print 'sing fun '
		time.sleep(1)

def dance(a):
	print ('dance get arg is %s' %a)
	for x in range(0,3):		
		print 'dance fun '
		time.sleep(1)
		
def main():
	a='jack'
	
	#start thread
	t=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
	print ('start time is %s' %t)
	
	sing(a)
	dance(a)
	
	print('this is master thread...')
	e=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
	print ('start time is %s' %e)
	

if __name__=="__main__":
	main()
	


 

对网上所说的python的伪多线程还是没有理解透彻,这个用多线程确实减少了时间呀,

此例中,难道是因为同一时刻交替执行,所以缩短了时间,而单线程则是在等待,不知这样理解正确不?

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值