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?
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
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
/proc/
are not files... they are eventually hooked up to some other things allowing you to set/get different things. you can load.so
files in python if you want to. but isn't 0.03s/1000times fast enough?