python:waitfor轮询

本文探讨了在处理时间不确定事件时,通过轮询机制替代直接睡眠的方法,以提高程序效率。通过实现一个自定义函数,该文展示了如何在给定时间内检查条件是否满足,从而避免了长时间等待或不必要的资源消耗。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时候需要等待一个时间不确定的事件的发生。如果直接sleep最大时长,然后判断预期,则严重影响效率。可以改用轮询机制,一旦条件满足,立即返回;反之等到最后超时。


def waitfor(getter, timeout=3, interval=0.5, *args):
	starttime = datetime.datetime.now()
	while True:
		if getter(args):
			return
		else:
			runtime = datetime.datetime.now() - starttime
			print runtime
			if runtime.seconds >= timeout:
				raise Exception
			time.sleep(interval)
	
current_value = 1	
def testgetval(args):
	wanted_value = args[0]
	global current_value
	current_value += 1
	print '%d, %d' % (wanted_value, current_value)
	return current_value > wanted_value	
		
if __name__ == '__main__':
	waitfor(testgetval, 1, 0.3, 2)
	print '======================='
	waitfor(testgetval, 1, 0.3, 8)

2, 2
0:00:00.001000
2, 3
====================
8, 4
0:00:00.002000
8, 5
0:00:00.303000
8, 6
0:00:00.605000
8, 7
0:00:00.907000
8, 8
0:00:01.209000
Traceback (most rece
  File "multiver.py"
    waitfor(testgetv
  File "multiver.py"
    raise Exception
Exception


第一轮测试,在1秒中内成功返回

第二轮测试,在预定的时间内未得到预期结果,抛出超时异常


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值