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
GETTING UPTIME ON WINDOWS OS For Windows, we would be using an inbuilt API function found in Windows OS under the name gettickcount64(). This function retrieves the number of milliseconds that have elapsed since the system was started.
Uptime Command In Linux: It is used to find out how long the system is active (running). This command returns set of values that involve, the current time, and the amount of time system is in running state, number of users currently logged into, and the load time for the past 1, 5 and 15 minutes respectively.
Using /proc/uptimeThe first number is the total number of seconds the system has been up. The second number is how much of that time the machine has spent idle, in seconds. On multi core systems (and some Linux versions) the second number is the sum of the idle time accumulated by each CPU.
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With