shell中分析各个命令执行时长的工具

在Shell中分析各个命令的执行时长,可以使用以下工具和方法:

1. 内置 time 命令

  • 功能:测量单个命令的执行时间。
  • 用法
    1
    time your_command
  • 注意:Bash内置的 time 和 GNU time(通常为 /usr/bin/time)输出格式不同。GNU 版本支持更多详细信息:
    1
    /usr/bin/time -v your_command

2. Bash 调试模式 + 时间戳

  • 功能:记录脚本中每个命令的执行时间。
  • 步骤
    1. 修改 PS4 变量以包含时间戳。
    2. 启用调试模式 set -x
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      #!/bin/bash
      PS4='+[$(date "+%T.%N")] ' # 设置时间戳格式
      exec 2> time.log # 重定向调试输出到文件
      set -x # 启用调试模式

      # 示例命令
      ls
      sleep 1

      set +x # 关闭调试模式
  • 分析:需手动处理 time.log,计算相邻命令的时间差。

3. ts 命令(来自 moreutils 包)

  • 功能:为命令输出添加时间戳。
  • 安装
    1
    2
    sudo apt install moreutils    # Debian/Ubuntu
    sudo yum install moreutils # RHEL/CentOS
  • 用法
    1
    your_command | ts "[%H:%M:%.S]"

4. perf 工具(系统级性能分析)

  • 功能:监控进程的系统级性能数据,包括执行时间。
  • 安装
    1
    sudo apt install linux-tools-common linux-tools-generic
  • 用法
    1
    2
    perf stat your_command       # 统计命令执行性能
    perf record -g your_command # 生成详细报告

5. Zsh 的 REPORTTIME 功能

  • 功能:自动报告执行时间超过阈值的命令(仅限 Zsh)。
  • 设置
    1
    REPORTTIME=5  # 报告超过5秒的命令

6. 自定义脚本(记录时间差)

  • 功能:手动插入时间记录。
  • 示例
    1
    2
    3
    4
    5
    start=$(date +%s.%N)
    your_command
    end=$(date +%s.%N)
    runtime=$(echo "$end - $start" | bc)
    echo "Time: $runtime seconds"

7. hyperfine(命令行基准测试工具)

  • 功能:多次运行命令并统计时间(适合比较不同命令的性能)。
  • 安装
    1
    sudo apt install hyperfine    # Debian/Ubuntu
  • 用法
    1
    hyperfine 'command1' 'command2'

总结

  • 单次命令:使用 timeperf stat
  • 脚本级分析:通过 Bash 调试模式输出时间戳,或手动插入时间记录。
  • 系统级监控perfdtrace(需学习成本)。
  • 基准测试hyperfine 或多次运行 time

选择工具时,根据需求权衡易用性与详细程度。