Fastest way to get system uptime in Python in Linux

后端 未结 5 808
無奈伤痛
無奈伤痛 2021-01-11 10:24

I\'m looking for a fast and lightweight way to read system uptime from a Python script. Is there a way to call the sysinfo Linux system call from Python?

<
相关标签:
5条回答
  • 2021-01-11 10:54

    I don't think you can get much faster than using ctypes to call sysinfo() but in my tests, its slower than /proc. Those linux system programmers seem to know what they are doing!

    import ctypes
    import struct
    
    def uptime3():
        libc = ctypes.CDLL('libc.so.6')
        buf = ctypes.create_string_buffer(4096) # generous buffer to hold
                                                # struct sysinfo
        if libc.sysinfo(buf) != 0:
            print('failed')
            return -1
    
        uptime = struct.unpack_from('@l', buf.raw)[0]
        return uptime
    

    Running your two tests plus mine on my slow laptop, I got:

    >>> print(timeit.timeit('ut.uptime1()', setup="import uptimecalls as ut", number=1000))
    5.284219555993332
    >>> print(timeit.timeit('ut.uptime2()', setup="import uptimecalls as ut", number=1000))
    0.1044210599939106
    >>> print(timeit.timeit('ut.uptime3()', setup="import uptimecalls as ut", number=1000))
    0.11733305400412064
    

    UPDATE

    Most of the time is spent pulling in libc and creating the buffer. If you plan to make the call repeatedly over time, then you can pull those steps out of the function and measure just the system call. In that case, this solution is the clear winner:

    uptime1: 5.066633300986723
    uptime2: 0.11561189399799332
    uptime3: 0.007740753993857652
    
    0 讨论(0)
  • 2021-01-11 10:54

    This frankly seems like a much better solution:

    def get_uptime():
        with open('/proc/uptime', 'r') as f:
            uptime_seconds = float(f.readline().split()[0])
    
        return uptime_seconds
    

    It also has the added benefit of not requiring any additional modules.

    Credits: Source

    0 讨论(0)
  • 2021-01-11 10:54

    Adding an UP TO DATE answer.

    This may not be the fastest way. But this is should be the replacement for psutil.boot_time() since I couldn't find boot_time in latest versions of linux psutil lib.

    Dependancy:

    pip3 install uptime
    

    Usage:

    >>> from uptime import uptime
    >>> uptime()
    49170.129999999997
    

    More info

    0 讨论(0)
  • 2021-01-11 10:56

    What about:

    import subprocess
    print(subprocess.check_output(['cat', '/proc/uptime']).decode('utf-8').split()[0])
    

    Not the fastest way but simple and direct

    0 讨论(0)
  • 2021-01-11 11:00

    You can try installing psutil with:

    pip install psutil
    

    and then use the following fragment of code:

    import psutil
    import time
    
    
    def seconds_elapsed():
        return time.time() - psutil.boot_time()
    
    
    print seconds_elapsed()
    
    0 讨论(0)
提交回复
热议问题