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

如何检测Python文件排序脚本运行时长?time模块使用遇阻求助

用Python time模块检测脚本运行时长的正确方法

以下是几种可靠的实现方式,直接套用到你的文件排序脚本里就行:

方法1:使用time.perf_counter()(推荐,精度最高)

这是Python官方推荐的用于测量短时间间隔的函数,精度比time.time()更高:

import time
# 导入你的文件排序所需模块,比如os等

def sort_files():
    # 这里是你的文件排序逻辑
    # 示例:按文件修改时间排序当前目录文件
    files = os.listdir('.')
    sorted_files = sorted(files, key=lambda x: os.path.getmtime(x))
    print("文件排序完成")

# 计时逻辑
start_time = time.perf_counter()
sort_files()  # 调用你的排序函数
end_time = time.perf_counter()

print(f"脚本运行时长: {end_time - start_time:.4f} 秒")

方法2:使用time.time()

如果不需要极高精度,也可以用这个获取当前时间戳的方法:

import time

start_time = time.time()
# 执行你的文件排序代码
your_sort_function()
end_time = time.time()

print(f"运行时长: {end_time - start_time:.2f} 秒")

方法3:用上下文管理器封装(优雅复用)

如果需要在多个地方计时,可以封装成上下文管理器,用with语句包裹代码块:

import time
from contextlib import contextmanager

@contextmanager
def timer():
    start = time.perf_counter()
    try:
        yield
    finally:
        end = time.perf_counter()
        print(f"耗时: {end - start:.4f} 秒")

# 使用方式
with timer():
    # 这里放你的文件排序代码
    sort_files()

你之前失败的可能原因

你提到系统提示"需输入真实时间",大概率是误用了time模块里需要参数的函数(比如time.strptime()需要输入时间字符串和格式,或者time.mktime()需要结构化时间对象),只要避开这些函数,用上面的perf_counter()或time()直接获取时间戳就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 00:09:22