插件窝 干货文章 linux查看进程运行时长

linux查看进程运行时长

进程 时间 运行 time 191    来源:    2025-04-05

在Linux系统中,查看进程的运行时长可以通过以下几种方法实现:


方法1:使用 ps 命令

ps -eo pid,comm,lstart,etime,time,args | grep <进程名或PID>
  • 关键字段说明
    • lstart:进程启动的具体日期和时间。
    • etime:进程已运行的总时长(格式为 DD-HH:MM:SS)。
    • time:进程消耗的CPU时间(注意不是实际运行时间)。
  • 示例bash ps -eo pid,comm,lstart,etime,time,args | grep nginx
    • 输出类似: 1234 nginx Mon Oct 2 14:30:00 2023 03:25:10 00:00:45 nginx: worker process
    • 表示进程已运行 3小时25分钟10秒

方法2:通过 /proc 文件系统

ls -ld /proc/<PID>/
  • 查看进程目录的创建时间(即启动时间),然后与当前时间计算差值。
  • 自动化脚本示例bash pid=1234 # 替换为目标PID start_time=$(stat -c %Y /proc/$pid) now=$(date +%s) seconds=$((now - start_time)) printf "Process has run for: %dd %dh %dm %ds\n" $((seconds/86400)) $((seconds%86400/3600)) $((seconds%3600/60)) $((seconds%60))

方法3:使用 tophtop

  1. top

    • 运行 top,按 c 显示完整命令,观察 TIME+ 列(CPU时间)。
    • 注意:TIME+ 是CPU占用时间,非实际运行时长。
  2. htop

    • 安装:sudo apt install htop(Debian/Ubuntu)或 sudo yum install htop(RHEL/CentOS)。
    • 运行 htop,在界面中直接查看 TIME+ 或启用 STARTTIME 列。

方法4:systemctl(仅限系统服务)

systemctl show <服务名> --property=ActiveEnterTimestamp
  • 计算与当前时间的差值: bash start=$(systemctl show nginx --property=ActiveEnterTimestamp | cut -d= -f2) now=$(date +%s) start_epoch=$(date -d "$start" +%s) echo "Service running for: $(( (now - start_epoch) / 60 )) minutes"

注意事项

  1. etime vs TIME
    • etime:进程从启动到现在的时间(实际运行时长)。
    • TIME:进程占用CPU的总时间(通常远小于实际时间)。
  2. 短寿命进程:若进程已结束,可通过审计工具(如 auditd)或日志查询历史记录。

总结

  • 推荐命令ps -eo pid,comm,lstart,etime | grep <PID>
  • 适用场景
    • 快速查看:pshtop
    • 精确计算:通过 /proc 或自定义脚本。

根据需求选择合适的方法即可获取进程的准确运行时长。