You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现超时控制:query_response耗时<2秒执行take_action否则执行abort_action

基于函数执行耗时的分支逻辑实现

要实现根据query_response的执行耗时决定后续执行哪个函数的逻辑,可借助Python的time模块精确统计函数运行时间,核心思路是记录函数执行前后的时间戳,计算耗时后进行分支判断。

完整实现代码

import time

def query_response():
    print("Query Response")
    # 可添加time.sleep(3)模拟超时场景,测试abort_action分支

def take_action():
    print("Take Action") 

def abort_action():
    print("Abort Action") 

# 计时与分支判断逻辑
start = time.perf_counter()
query_response()
cost = time.perf_counter() - start

if cost < 2:
    take_action()
else:
    abort_action()

关键说明

  • 使用time.perf_counter()统计时间:该函数返回系统运行的精确时间,适合短时间间隔计时,精度比time.time()更高。
  • 分支判断逻辑:计算query_response执行完成后的耗时,若小于2秒则调用take_action,否则调用abort_action。
  • 测试场景:如果需要验证超时分支,可在query_response函数内添加time.sleep(3),此时耗时会超过2秒,自动触发abort_action。

内容的提问来源于stack exchange,提问作者Ahmad Ismail

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 07:15:54