Fastest way to get system uptime in Python in Linux

python get system uptime windows
proc/uptime
psutil
psutil get pid
psutil kill process
psutil temperature
psutil nosuchprocess
python get cpu usage of process

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

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

uptime, Therefore, it also provides a way to get at that: uptime.boottime(). Debian Linux 6.0.6, ✓, _uptime_linux(), _uptime_posix(), Every Linux since ~1994, Cygwin. 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.

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()

System uptime in Python, a better way | Blog, I've been working on a system monitoring tool which needs determine whether the uptime of a Linux slave machine has changed since it last  System uptime in Python, a better way. Published Thu, 26th Jan '12. I've been working on a system monitoring tool which needs determine whether the uptime of a Linux slave machine has changed since it last reported in. I looked through Python's online documentation and it turns out that there isn't a function among the standard modules for

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

Easy Ways to Find Linux System/Server Uptime, Method-2: How to Check Linux System Uptime Using the w Command. The “w” command provides a quick summary of every user logged into a computer, what​  Finding system information in Ubuntu like Number and type of processors, memory usage, uptime etc are extremely easy. You can use Linux system commands like free -m , uname -a and uptime to find these details. But there is no fun in doing that. If you love coding in python, you want to do everything in python.

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

Getting System Information in Linux using Python script - DEV, Finding system information in Ubuntu like Number and type of You can use Linux system commands like free -m, uname -a and uptime to find these details. So we will see how to find this information using the python program. Create templates to quickly answer FAQs or store snippets for re-use. Below are the 4 ways to find out uptime of system. Command 1 : uptime. In below output it shows system is up 8 minutes ago. linux@mypc:~$ uptime 20:43:50 up 8 min, 2 users, load average: 0.94, 0.82, 0.48 linux@mypc:~$ Command 2: cat /proc/uptime. The first number is how long the system has been up(in seconds).

What about:

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

Not the fastest way but simple and direct

Tuptime - A CLI Utility To Find Linux System Uptime, Tuptime is a command line utility written in Python that reports the In this guide, we will see how to find Linux system uptime using Tuptime utility. and 49 seconds from 07:24:35 AM 01/20/2020 Shortest uptime: 15 minutes  Uptime command is available under procps package. This command also provides the current system time, number of logged in users and current CPU load. uptime 07:33:31 up 174 days, 5:12, 2 users, load average: 0.17, 0.14, 0.17. as per the above output, the system is running from 174 days, 5 hours and 12 minutes.

How to Execute Shell Commands with Python, You'll learn here how to do just that with the os and subprocess modules. You will find the output in the command line where you have started -a\n") ssh.stdin.​write("uptime\n") ssh.stdin.close() # Fetch output for line in For a short and quick script you might just want to use the os.system() or os.popen()  BSD-specific uptime (including OS X). It uses sysctl (through the sysctlbyname() function) to figure out the system’s boot time, which it then subtracts from the current time to find the uptime. uptime._uptime_linux()¶ Linux-specific uptime. It first tries to read /proc/uptime, and if that fails, it calls the sysinfo() C function.

tuptime, Calculate the accumulated system uptime, downtime and total. Python 2.7 or 3.​x installed but latest version is recommended. In this article, we have looked at ways of using tuptime command for System TecMint is the fastest growing and most trusted community site for any kind of Linux Articles,  I've been trying to find a way to get the time since 1970-01-01 00:00:00 UTC in seconds and nanoseconds in python and I cannot find anything that will give me the proper precision. I have tried using time module, but that precision is only to microseconds, so the code I tried was: import time print time.time() which gave me a result like this:

Python Tutorial: ssh remote run of a local file - 2020, So, in this chapter, we'll see how we can run our code remotely and get the outputs from it. In this chapter, I used my server at http://www.bogotobogo.com/ as a remote s.py #!/usr/bin/python import subprocess cmd_list = ['uname -r', '​uptime'] out 0.12.7 - Fast and simple WSGI-micro framework for small web-​applications . I would like to get the system uptime from within a C application running on a linux-based system. I don't want to call uptime(1) and parse the output, I'd like to call the underlying C API I suspect exists. Anyone know if there is such a call, or does uptime(1) simply process records obtained from wtmp?

Comments
  • files in /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?
  • Indeed they do... Thanks. However, on a second thought, I believe this can be optimized by taking the first one or two lines out of the function call.
  • This is what I get with libs and buffer as global variables: uptime1: 1.8627383150014794 uptime2: 0.03709090399206616 uptime3: 0.0018650189886102453
  • But basically you answered my question by showing how to call C library functions from Python.
  • I put it into the def to factor in the cost of getting the libc reference. If you plan to call this multiple times in a single program, then pulling it out of the function to test the timing is legitimate. Retesting, I got 5.066633300986723, 0.11561189399799332, 0.007740753993857652. Looks like we beat those slacker system programmers after all.
  • i would be very surprised that this can be significantly faster than approach 2: github.com/giampaolo/psutil/blob/master/psutil/…
  • Me too but maybe it's the fastest cross platform and portable solution even if the OP asks for linux
  • This answer is boring. It's much too simple! ... (joking) I want to say: Thank you for this nice answer.
  • Use psutil.boot_time() if running a more modern version of psutil.