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

Python 2.7中如何测量函数B执行时长并在函数A中返回结果

Python 2.7 测量函数执行耗时的实现方案

在Python 2.7中,可借助time模块实现函数B的执行耗时测量,直接修改函数A即可完成需求,具体代码如下:

import time

def A(B):
    # 记录函数B执行前的时间戳
    time_before = time.time()
    # 调用目标函数B
    B()
    # 记录函数B执行后的时间戳
    time_after = time.time()
    # 计算并返回耗时(单位:秒,浮点数)
    return time_after - time_before

补充说明

  • 上述代码用time.time()获取Unix时间戳,计算的是实际流逝时间,适合大多数普通场景。
  • 如果需要测量函数B占用CPU的实际执行时间(排除系统等待、IO等耗时),可替换为time.clock():
    import time
    
    def A(B):
        time_before = time.clock()
        B()
        time_after = time.clock()
        return time_after - time_before
    
    注:time.clock()在Python 3.3+被废弃,但Python 2.7中可正常使用。

测试示例

你可以用以下代码验证功能:

def test_B():
    # 模拟一个耗时操作
    for _ in range(1000000):
        pass

# 调用A函数测量test_B的耗时
cost = A(test_B)
print("函数B执行耗时:{} 秒".format(cost))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:02:38