Issue
for a project of mine i need to detect the current incoming megabytes per second on linux coded in python.
i found someone elses code that does the correct thing but its coded in java and i dont exactly understand it. any pointers?
TOTAL_INCOMING_BYTES_FILE = "/sys/class/net/%s/statistics/rx_bytes",
final double current_mbps =
((current_total_bytes - Long.parseLong(Files.readAllLines(Paths.get(new File(String.format(TOTAL_INCOMING_BYTES_FILE, ETH_INTERFACE)).toURI())).get(0))) / 125000) * (-1);
Solution
i found someone elses code that does the correct thing but its coded in java and i dont exactly understand it.
Indeed Long.parseLong(Files.readAllLines(Paths.get(new File(String.format(TOTAL_INCOMING_BYTES_FILE, ETH_INTERFACE)).toURI())).get(0))
is an incredibly convoluted way to read a number from a file, and to take the abstruseness a bit further the fraction of a difference is multiplied by −1 instead of exchanging the subtrahend and the minuend.
With the constant 125000 the expression computes the current_mbps
if current_total_bytes
has been fetched one eighth of a second ago (since 125000 is one eighth of a million). The (re-)initialization of current_total_bytes
is missing from the code.
Here's a Python snippet for the computation of e. g. the eth0
rate:
import time
earlier_total_bytes = None
while 0 <= (current_total_bytes := int(open("/sys/class/net/eth0/statistics/rx_bytes").read())) \
and earlier_total_bytes is None: earlier_total_bytes = current_total_bytes; time.sleep(.125)
current_mbps = (current_total_bytes - earlier_total_bytes) / 125000
Of course this can be adapted for other sampling intervals, also repeated and variable.
Answered By - Armali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.