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

2020-02-26 10:32发布

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 seconds?

  • Please assume at least 3 digits for the days part as I don't know how long it can be.
  • The output will be egreped to one only line so no need for a loop.

14条回答
别忘想泡老子
2楼-- · 2020-02-26 11:09

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
查看更多
够拽才男人
3楼-- · 2020-02-26 11:09

A version for Python:

ex=[
    '21-18:26:30',
    '06-00:15:30',
    '15:28:37',
    '48:14',
    '00:01'
    ]

def etime_to_secs(e):
    t=e.replace('-',':').split(':')
    t=[0]*(4-len(t))+[int(i) for i in t]
    return t[0]*86400+t[1]*3600+t[2]*60+t[3]

for e in ex:
    print('{:11s}: {:d}'.format(e, etime_to_secs(e)))
查看更多
登录 后发表回答