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

Python subprocess调用time命令输出陌生后缀的原因及含义解析

问题解析:subprocess调用time与直接执行输出差异及字段说明

为什么输出格式不同?

直接在终端执行time ls时,用的是Shell内置的time命令,它的输出是简洁的real/user/sys三行格式;而你用subprocess.Popen调用的是独立的二进制程序/usr/bin/time,这个程序会输出更详细的进程资源使用统计信息,就是你看到的带陌生后缀的那行内容。

陌生后缀字段详解

那串后缀里的每个部分都是进程资源使用的统计项:

  • 91%CPU:进程的CPU使用率,计算公式为 (user时间 + system时间) / elapsed时间 * 100%,这里因为elapsed时间极短(接近0),所以百分比看起来偏高
  • 0avgtext:进程运行期间,文本段(可执行代码区)的平均占用内存大小,单位是KB
  • 0avgdata:进程运行期间,数据段+栈区的平均占用内存大小,单位是KB
  • 2264maxresident:进程生命周期内占用的最大驻留集大小(即实际使用的物理内存峰值),单位是KB
  • 末尾的k:明确标注前面所有内存相关数值的单位是KB

第一行内容的解析示例

如果要提取这行里的关键信息(比如user时间、system时间、CPU使用率等),可以用字符串分割或者正则表达式来处理,以下是Python示例:

方法1:字符串分割

import subprocess

p = subprocess.Popen(['time', 'ls'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stderr_output = p.stderr.read().decode('utf-8').strip()
# 分割成字段
parts = stderr_output.split()
user_time = parts[0]
system_time = parts[2]
elapsed_time = parts[4]
cpu_usage = parts[5]
max_resident = parts[8].rstrip(')k')

print(f"用户态时间: {user_time}")
print(f"内核态时间: {system_time}")
print(f"总耗时: {elapsed_time}")
print(f"CPU使用率: {cpu_usage}")
print(f"最大物理内存占用: {max_resident}KB")

方法2:正则表达式匹配

import subprocess
import re

p = subprocess.Popen(['time', 'ls'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stderr_output = p.stderr.read().decode('utf-8').strip()
pattern = r'(\d+\.\d+)user (\d+\.\d+)system (\d+:\d+\.\d+)elapsed (\d+)%CPU \((\d+)avgtext\+(\d+)avgdata (\d+)maxresident\)k'
match = re.match(pattern, stderr_output)
if match:
    user_time, system_time, elapsed_time, cpu_usage, avgtext, avgdata, maxresident = match.groups()
    print(f"用户态时间: {user_time}s")
    print(f"内核态时间: {system_time}s")
    print(f"总耗时: {elapsed_time}")
    print(f"CPU使用率: {cpu_usage}%")
    print(f"平均文本段内存: {avgtext}KB")
    print(f"平均数据栈内存: {avgdata}KB")
    print(f"最大物理内存占用: {maxresident}KB")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 22:41:30