在Linux中使用Python获得系统正常运行时间的最快方法 [英] Fastest way to get system uptime in Python in Linux
问题描述
我正在寻找一种快速,轻便的方法来从Python脚本读取系统正常运行时间.有没有办法从Python调用sysinfo
Linux系统调用?
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?
到目前为止,我发现了另外两种测量正常运行时间的方法,一种涉及运行外部进程,另一种涉及读取/proc
中的文件.
So far I've found two other methods for measuring uptime, one that involves running an external processes and one that involves reading a file in /proc
.
import subprocess
def uptime1():
raw = subprocess.check_output('uptime').decode("utf8").replace(',', '')
days = int(raw.split()[2])
if 'min' in raw:
hours = 0
minutes = int(raw[4])
else:
hours, minutes = map(int,raw.split()[4].split(':'))
totalsecs = ((days * 24 + hours) * 60 + minutes) * 60
return totalsecs
def uptime2():
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.readline().split()[0])
return uptime_seconds
比较速度时,第二种方法快50倍左右.尽管如此,直接调用系统调用还是要好一个数量级.
When comparing the speed, the second method is around 50 times faster. Still, calling a system call directly should be yet another order of magnitude better.
>> import timeit
>> print(timeit.timeit('ut.uptime1()', setup="import uptimecalls as ut", number=1000))
1.7286969429987948
>> print(timeit.timeit('ut.uptime2()', setup="import uptimecalls as ut", number=1000))
0.03355383600865025
推荐答案
我认为您不会比使用ctypes
调用sysinfo()
更快,但是在我的测试中,它比/proc慢.那些linux系统程序员似乎知道他们在做什么!
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
更新
大部分时间都花在拉入libc
和创建缓冲区上.如果您打算随着时间的推移反复进行调用,则可以将这些步骤从功能中撤出并仅测量系统调用.在这种情况下,这种解决方案无疑是赢家:
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
这篇关于在Linux中使用Python获得系统正常运行时间的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!