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

Python计时装饰器报错TypeError:不支持函数与浮点数相减

问题排查与解决:计算函数运行时长的装饰器错误

错误原因

报错TypeError: unsupported operand type(s) for -: 'builtin_function_or_method' and 'float'的核心问题是:你赋值给end_time的是time.time这个函数对象,而非调用它获取的浮点型时间戳。start_time是通过time.time()得到的时间戳(float类型),而end_time是函数本身,两者无法执行减法运算。

修正后的代码

import time

def timmer(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()  # 补充括号,调用函数获取当前时间戳
        print(f"{func.__name__} ran in {end_time - start_time} seconds")
        return result
    return wrapper

@timmer
def example_function(n):
    time.sleep(n)
    
example_function(2)

可选优化

如果想让输出的时长更美观,可以格式化保留指定小数位数:

print(f"{func.__name__} ran in {end_time - start_time:.2f} seconds")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 22:52:05