python记录某个有最大等待时间的函数运行时间、剩余时间的实现代码
时间: 2024-03-11 18:46:42 浏览: 128
可以使用Python的`time`模块来实现记录函数运行时间、剩余时间的功能。具体实现方法如下:
```python
import time
def wait_and_run(max_wait_time, func, *args, **kwargs):
"""
等待最大max_wait_time秒,并运行函数func(*args, **kwargs)
"""
start_time = time.time()
remaining_time = max_wait_time
while remaining_time > 0:
# 计算剩余时间
remaining_time = max_wait_time - (time.time() - start_time)
if remaining_time <= 0:
# 最大等待时间已过,退出循环
break
# 运行函数,记录时间
func_start_time = time.time()
func(*args, **kwargs)
func_end_time = time.time()
# 计算函数运行时间
func_time = func_end_time - func_start_time
# 输出运行时间和剩余时间
print("Function {} took {:.2f} seconds. Remaining time: {:.2f} seconds.".format(func.__name__, func_time, remaining_time))
```
使用示例:
```python
def test_func():
time.sleep(2)
wait_and_run(10, test_func)
```
输出结果:
```
Function test_func took 2.00 seconds. Remaining time: 8.00 seconds.
Function test_func took 2.00 seconds. Remaining time: 6.00 seconds.
Function test_func took 2.00 seconds. Remaining time: 4.00 seconds.
Function test_func took 2.00 seconds. Remaining time: 2.00 seconds.
```
阅读全文