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

在Python脚本中调用Linux time命令统计C程序执行时间的问题

在Python中计算C程序执行时间的正确姿势

看起来你想用Python脚本统计C可执行文件test.out的运行时间,还需要处理输入输出重定向,但目前用os.system()配合shell的time命令得到的输出太冗余,而且可能遇到了重定向或者提取时间的问题。我给你几个更靠谱的解决方案:

方案1:用Python自带的time模块直接计时(最推荐)

不需要依赖shell的time命令,直接在Python里记录程序启动和结束的时间,简单又可控:

import subprocess
import time

# 记录开始时间
start = time.time()

# 执行C程序,同时重定向输入输出
with open("inp", "r") as in_file, open("out", "w") as out_file:
    # subprocess.run比os.system更安全,还能捕获错误
    subprocess.run(["./test.out"], stdin=in_file, stdout=out_file, check=True)

# 计算耗时
elapsed_time = time.time() - start
print(f"C程序执行时间:{elapsed_time:.4f} 秒")

这个方法的好处是完全在Python生态里处理,不用管shell的各种输出格式问题,结果就是程序从启动到结束的真实耗时。

方案2:用GNU time命令自定义输出格式

如果你一定要用time命令来获取系统级的详细计时(比如用户态、内核态时间),可以用GNU版本的time(通常路径是/usr/bin/time,不是shell内置的time),它支持自定义输出格式,能直接输出你想要的时间:

import subprocess

# 用/usr/bin/time的-f参数指定输出仅为耗时(%e代表elapsed时间,单位秒)
result = subprocess.run(
    ["/usr/bin/time", "-f", "%e", "./test.out"],
    stdin=open("inp", "r"),
    stdout=open("out", "w"),
    stderr=subprocess.PIPE,  # time的输出会到stderr
    text=True,
    check=True
)

# 从stderr里提取干净的时间
exe_time = result.stderr.strip()
print(f"C程序执行时间:{exe_time} 秒")

如果需要其他统计信息,比如用户态时间(%U)、系统态时间(%S),可以修改-f的参数,比如-f "user:%U system:%S elapsed:%e",这样输出的信息更丰富但依然整洁。

方案3:解析你原来的time输出(兼容旧场景)

如果已经生成了像0.00user 0.00system 0:00.00elapsed ...这样的冗余输出,也可以用正则表达式提取出elapsed时间:

import re

# 读取exe_time文件的内容
with open("exe_time", "r") as f:
    time_log = f.read()

# 用正则匹配elapsed部分
match_result = re.search(r"(\d+:\d+\.\d+)elapsed", time_log)
if match_result:
    elapsed_str = match_result.group(1)
    # 把分:秒转换成总秒数
    mins, secs = elapsed_str.split(":")
    total_secs = int(mins) * 60 + float(secs)
    print(f"提取到的执行时间:{total_secs:.4f} 秒")
else:
    print("无法从输出中提取执行时间")

为什么不推荐用os.system()?

os.system()只能返回命令的退出码,没法直接捕获输出,你只能通过文件重定向来保存结果,灵活性很差。而subprocess模块是Python官方推荐的替代方案,支持更细粒度的控制,比如捕获stdout/stderr、设置超时、避免shell注入风险等等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 06:54:54