Fastest way to get system uptime in Python in Linux

后端 未结 5 852
無奈伤痛
無奈伤痛 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
    

提交回复
热议问题