Parse ps' “etime” output and convert it into seconds

后端 未结 14 2113
难免孤独
难免孤独 2020-12-30 12:43

These are possible output formats for ps h -eo etime

21-18:26:30
   15:28:37
      48:14
      00:01

How to parse them into se

14条回答
  •  情歌与酒
    2020-12-30 13:10

    I just had to add my version, heavily based on the elegant perl one-liner by @andor (beautiful perl code!)

    • time : total CPU time since beginning (? or some computation of it, that is decayed if cpu usage goes down? I am not sure.... a high number signals a cpu intensive process, though)
    • etime: total time elapsed since the process started
    • the 2 ways for tail : on linux : tail +2 doesn't work. On solaris, tail -n +2 doesn't work. So I try both to be sure.

    Here is how to compute the times and also sort your processes by their mean CPU usage over time

    ps -eo pid,comm,etime,time | { tail +2 2>/dev/null || tail -n +2 ;} | perl -ane '
        @e=reverse split(/[:-]/,$F[2]); $se=$e[0]+$e[1]*60+$e[2]*3600+$e[3]*86400;
        @t=reverse split(/[:-]/,$F[3]); $st=$t[0]+$t[1]*60+$t[2]*3600+$t[4]*86400; 
        if ( $se == 0 ) { $pct=0 ; } else { $pct=$st/$se ;};
        printf "%s\t%s\t%s(%sseconds)\t%s(%sseconds)\t%.4f%%\n",$F[0],$F[1],$F[2],$se,$F[3],$st,$pct*100;
       '  | sort -k5,5n
    

提交回复
热议问题