macOS/Ubuntu统计命令运行时间

2025-11-11
#Unix #macOS #Ubuntu

1. 前言

macOS 或 Ubuntu 在运行过长时间终端命令时,需要统计程序运行的时间。

2. 步骤

run_with_timer.sh 详细代码:

#!/bin/bash
# 用法: ./run_with_timer.sh bash job.sh

# 定义日志文件(可按日期分文件)
LOG_DIR="$HOME/job_logs"
mkdir -p "$LOG_DIR"
LOG_FILE="$LOG_DIR/$(date +%Y-%m-%d).log"

# 获取开始时间
start_time=$(date +%s)
start_str=$(date "+%Y-%m-%d %H:%M:%S")

# 执行命令
echo "[$start_str] 开始执行命令:$*" | tee -a "$LOG_FILE"
"$@"
exit_code=$?

# 获取结束时间与耗时
end_time=$(date +%s)
end_str=$(date "+%Y-%m-%d %H:%M:%S")
duration=$((end_time - start_time))

# 记录日志
days=$((duration/86400))
hours=$((duration%86400/3600))
mins=$((duration%3600/60))
secs=$((duration%60))
printf "[%s] 命令结束,耗时:%02d天%02d小时%02d分%02d秒,退出码:%d\n\n" \
  "$end_str" "$days" "$hours" "$mins" "$secs" "$exit_code" | tee -a "$LOG_FILE"

Ubuntu 操作步骤:

# 让脚本可执行
chmod +x run_with_timer.sh

# 系统全局使用
sudo cp run_with_timer.sh /usr/local/bin/
sudo chmod +x /usr/local/bin/run_with_timer.sh

# 运行任务
run_with_timer.sh bash job.sh

# 查看日志
cat ~/job_logs/2025-11-11.log

运行效果:

[2025-11-11 10:30:05] 开始执行命令:bash job.sh
[2025-11-11 10:32:18] 命令结束,耗时:02分13秒,退出码:0

另外, macOS 可放在个人脚本目录:

mkdir -p ~/bin
mv run_with_timer.sh ~/bin/
chmod +x ~/bin/run_with_timer.sh
echo 'export PATH="$HOME/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc