代码之家  ›  专栏  ›  技术社区  ›  stanleyxu2005

如何在python中检索进程开始时间(或正常运行时间)

  •  30
  • stanleyxu2005  · 技术社区  · 15 年前

    我只知道,我可以调用“ps-p my\u process\u id-f”,然后解析输出。但这并不酷。

    6 回复  |  直到 15 年前
        1
  •  21
  •   Daniel G    15 年前

    如果您是在试图度量的python程序中执行此操作,则可以执行以下操作:

    import time
    # at the beginning of the script
    startTime = time.time()
    # ...
    def getUptime():
        """
        Returns the number of seconds since the program started.
        """
        # do return startTime if you just want the process start time
        return time.time() - startTime
    

    否则,您别无选择,只能解析 ps /proc/pid . 一个不错的 bash 获取经过时间的方法是:

    ps -eo pid,etime | grep $YOUR_PID | awk '{print $2}'
    

    这只会以以下格式打印经过的时间,因此应该很容易解析:

    days-HH:MM:SS
    

    HH:MM:SS )

    ps -eo pid,stime | grep $YOUR_PID | awk '{print $2}'
    

    不幸的是,如果你的过程没有开始

    import sys
    import datetime
    import time
    import subprocess
    
    # call like this: python startTime.py $PID
    
    pid = sys.argv[1]
    proc = subprocess.Popen(['ps','-eo','pid,etime'], stdout=subprocess.PIPE)
    # get data from stdout
    proc.wait()
    results = proc.stdout.readlines()
    # parse data (should only be one)
    for result in results:
        try:
            result.strip()
            if result.split()[0] == pid:
                pidInfo = result.split()[1]
                # stop after the first one we find
                break
        except IndexError:
            pass # ignore it
    else:
        # didn't find one
        print "Process PID", pid, "doesn't seem to exist!"
        sys.exit(0)
    pidInfo = [result.split()[1] for result in results
               if result.split()[0] == pid][0]
    pidInfo = pidInfo.partition("-")
    if pidInfo[1] == '-':
        # there is a day
        days = int(pidInfo[0])
        rest = pidInfo[2].split(":")
        hours = int(rest[0])
        minutes = int(rest[1])
        seconds = int(rest[2])
    else:
        days = 0
        rest = pidInfo[0].split(":")
        if len(rest) == 3:
            hours = int(rest[0])
            minutes = int(rest[1])
            seconds = int(rest[2])
        elif len(rest) == 2:
            hours = 0
            minutes = int(rest[0])
            seconds = int(rest[1])
        else:
            hours = 0
            minutes = 0
            seconds = int(rest[0])
    
    # get the start time
    secondsSinceStart = days*24*3600 + hours*3600 + minutes*60 + seconds
    # unix time (in seconds) of start
    startTime = time.time() - secondsSinceStart
    # final result
    print "Process started on",
    print datetime.datetime.fromtimestamp(startTime).strftime("%a %b %d at %I:%M:%S %p")
    
        2
  •  69
  •   λuser    8 年前

    使用psutil https://github.com/giampaolo/psutil :

    >>> import psutil, os, time
    >>> p = psutil.Process(os.getpid())
    >>> p.create_time()
    1293678383.0799999
    >>> time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(p.create_time()))
    '2010-12-30 04:06:23'
    >>>
    

    …而且它是跨平台的,不仅仅是Linux。

        3
  •  15
  •   badp    15 年前

    man proc 上面说第22项 /proc/my_process_id/stat 是:

    starttime %lu

    进程在系统引导后启动的时间(单位:秒)。

    现在的问题是,如何确定一个jiffy的长度以及如何确定系统何时启动。

    人工程序 :在里面 /proc/stat ,就像这样:

    btime 1270710844
    


    前者的答案我不确定。 man 7 time 说:

    软件时钟、HZ和Jiffies

    许多系统调用和时间戳的准确性受到软件时钟分辨率的限制,软件时钟是由内核维护的时钟,用于测量jiffies中的时间。 jiffy的大小由内核常量的值决定 HZ . 价值 赫兹 赫兹 为100,给出0.01秒的jiffy值;从2.6.0开始, 赫兹 被提升到1000,给予0.001秒的跳跃;从内核2.6.13开始 值是内核配置参数,可以是100、250(默认值)或1000,产生的jiffies值分别为0.01、0.004或0.001秒。

    我们需要找到

    ps 因此:

      /* sysinfo.c init_libproc() */
      if(linux_version_code > LINUX_VERSION(2, 4, 0)){ 
        Hertz = find_elf_note(AT_CLKTCK);
        //error handling
      }
      old_Hertz_hack(); //ugh
    

        4
  •  6
  •   Dan Benamy    13 年前

    以下代码基于badp的答案:

    import os
    from time import time
    
    HZ = os.sysconf(os.sysconf_names['SC_CLK_TCK'])
    
    def proc_age_secs():
        system_stats = open('/proc/stat').readlines()
        process_stats = open('/proc/self/stat').read().split()
        for line in system_stats:
            if line.startswith('btime'):
                boot_timestamp = int(line.split()[1])
        age_from_boot_jiffies = int(process_stats[21])
        age_from_boot_timestamp = age_from_boot_jiffies / HZ
        age_timestamp = boot_timestamp + age_from_boot_timestamp
        return time() - age_timestamp
    

    不过,我不确定这是否正确。我编写了一个调用sleep(5)的测试程序,然后运行它,结果是错误的,从一次运行到另一次运行需要几秒钟的时间。这在vmware workstation虚拟机中:

    if __name__ == '__main__':
        from time import sleep
        sleep(5)
        print proc_age_secs()
    

    输出为:

    $ time python test.py
    6.19169998169
    
    real    0m5.063s
    user    0m0.020s
    sys     0m0.036s
    
        5
  •  3
  •   Wilfred Hughes AntuanSoft    9 年前
    def proc_starttime(pid=os.getpid()):
        # https://gist.github.com/westhood/1073585
        p = re.compile(r"^btime (\d+)$", re.MULTILINE)
        with open("/proc/stat") as f:
            m = p.search(f.read())
        btime = int(m.groups()[0])
    
        clk_tck = os.sysconf(os.sysconf_names["SC_CLK_TCK"])
        with open("/proc/%d/stat" % pid) as f:
            stime = int(f.read().split()[21]) / clk_tck
    
        return datetime.fromtimestamp(btime + stime)
    
        6
  •  1
  •   ghostdog74    15 年前

    /proc/uptime

    >>> uptime, idletime = [float(f) for f in open("/proc/uptime").read().split()]
    >>> print uptime
    29708.1
    >>> print idletime
    26484.45
    

    对于windows机器,您可能可以使用 wmi

    import wmi
    c = wmi.WMI()
    secs_up = int([uptime.SystemUpTime for uptime in c.Win32_PerfFormattedData_PerfOS_System()][0])
    hours_up = secs_up / 3600
    print hours_up