anyio.sleep() timing inconsistencies at small sleep times between asyncio and trio - python

python 3.9.5 (anyio, asyncio, trio)
windows 10
I am attempting to use anyio.sleep() to limit how fast my main app loop is running, in addition to having another async loop in a class running as a task. I've noticed when I decrease the sleep period (increase the refresh rate), asyncio seems to report incorrect, very short sleep times (high refresh rate) while trio seems to be reporting more expected values.
additionally, when the start function loop period is lower than the main loop refresh rate, asyncio seems to give unpredictable results. at higher than 40 hz, asyncio seems to refresh faster than intended, getting exponentially worse when inputting high refresh rates.
in the code sample below, FPSCounter is just a helper class. the whole block is copy-and-paste runnable.
here are some testing results with varying refresh rates by using the code at the bottom.
********** start hz: 33.33 / main hz 60.0 **********
============= trio =============
start function refresh rate (hz)
avg: 32.111337719289175
max: 32.20671951236294
min: 32.01595592621541
main function refresh rate (hz)
avg: 57.98613394545777
max: 58.00646191985787
min: 57.96580597105768
============= asyncio =============
start function refresh rate (hz)
avg: 58.18328943732051
max: 58.22729607295037
min: 58.13928280169065
main function refresh rate (hz)
avg: 58.184786967810574
max: 58.22527199837126
min: 58.144301937249885
********** start hz: 40.0 / main hz 240.0 **********
============= trio =============
start function refresh rate (hz)
avg: 39.234583680312994
max: 39.38072626526089
min: 39.0884410953651
main function refresh rate (hz)
avg: 215.89497360297648
max: 216.52241650591293
min: 215.26753070004003
============= asyncio =============
start function refresh rate (hz)
avg: 64.0348432659224
max: 64.04419798485424
min: 64.02548854699056
main function refresh rate (hz)
avg: 191.6032335310934
max: 192.06711593299164
min: 191.13935112919512
********** start hz: 80.0 / main hz 240.0 **********
============= trio =============
start function refresh rate (hz)
avg: 74.98626248669126
max: 75.31187257068325
min: 74.66065240269926
main function refresh rate (hz)
avg: 220.92863862387009
max: 222.9905452008835
min: 218.86673204685667
============= asyncio =============
start function refresh rate (hz)
avg: 461.9392486786134
max: 732.8401458173149
min: 191.0383515399119
main function refresh rate (hz)
avg: 460.52822045374194
max: 730.0229804121695
min: 191.0334604953143
import anyio
from time import perf_counter_ns
from collections import deque
class FPSCounter:
def __init__(self):
self.current_fps = 0
self.previous_fps = 0
self.last_time = 0
self.update_interval = 1 #sec
self.frame_times = deque()
self.intervals = []
self.history = []
def new_frame(self):
self.frame_times.append(perf_counter_ns())
def update_fps(self):
if (len(self.frame_times) < 2):
if(len(self.frame_times) == 0 or
(perf_counter_ns() > (self.frame_times.pop() + 2*1_000_000_000*self.update_interval))):
self.previous_fps = self.current_fps
self.current_fps = 0
else:
if (self.last_time == 0):
self.last_time = self.frame_times.popleft()
while(len(self.frame_times) > 0):
t = self.frame_times.popleft()
if t > self.last_time:
self.intervals.append(t-self.last_time)
self.last_time = t
if len(self.intervals) == 0: return
avg = sum(self.intervals) / len(self.intervals)
self.previous_fps = self.current_fps
self.current_fps = 1_000_000_000.0 / float(avg)
self.intervals.clear()
self.history.append(self.current_fps)
async def start(fps: float, counter: FPSCounter, duration):
last_time = anyio.current_time()
with anyio.move_on_after(duration) as scope:
while True:
counter.new_frame()
last_time = anyio.current_time()
# group of tasks to do this loop
async with anyio.create_task_group() as tg:
# sleep to cause refresh rate
await anyio.sleep(1.0/fps - anyio.current_time() + last_time)
# do stuff
async def main(start_loop_hz, main_loop_hz):
fps_start = FPSCounter()
fps_main = FPSCounter()
last_fps_update = anyio.current_time()
start_time = anyio.current_time()
last_time = anyio.current_time()
duration = 3.0
# main group to start background 'start' coro
async with anyio.create_task_group() as maintg:
maintg.start_soon(start, start_hz, fps_start, duration)
# main app loop
with anyio.move_on_after(duration) as scope:
while anyio.current_time() < (start_time+duration):
fps_main.new_frame()
last_time = anyio.current_time()
if (anyio.current_time() - last_fps_update) > 1.0:
last_fps_update = anyio.current_time()
fps_main.update_fps()
fps_start.update_fps()
# sleep to cause the refresh rate for main loop
await anyio.sleep(1.0/(main_hz) - anyio.current_time() + last_time)
# do stuff in main app loop
fps_start_avg = sum(fps_start.history) / len(fps_start.history)
fps_start_max = max(fps_start.history)
fps_start_min = min(fps_start.history)
print(f'start function refresh rate (hz)\navg: {fps_start_avg}\nmax: {fps_start_max}\nmin: {fps_start_min}')
fps_main_avg = sum(fps_main.history) / len(fps_main.history)
fps_main_max = max(fps_main.history)
fps_main_min = min(fps_main.history)
print(f'main function refresh rate (hz)\navg: {fps_main_avg}\nmax: {fps_main_max}\nmin: {fps_main_min}')
# exit()
if __name__ == '__main__':
start_hz = 33.33 # refresh rate for the start function loop
main_hz = 60.0 # refresh rate for the main loop
print(f'********** start hz: {start_hz} / main hz {main_hz} **********')
print('============= trio =============')
anyio.run(main, start_hz, main_hz, backend='trio')
print('============= asyncio =============')
anyio.run(main, start_hz, main_hz, backend='asyncio')

Related

Need to get mean and max values with this script

I'm having a few problems.
First, given wind speeds seem to be low, especially compared to other weather stations reporting close by (apparently there are lots of enthusiasts in my area). Just watching the trees, flag, bushes, small animals flying across my yard, I can tell 1.6mph is a wee bit low. Everything tested fine inside, and when I run the test script outside its picking up the signal as it spins.
the 2nd problem is it always reports the "mean" and "max" speeds as exactly the same. I've tried to adjust the intervals, but no matter what length of time I put in, they always report as the same numbers.
from gpiozero import Button
import requests
import time
import math
import statistics
import database
wind_count = 0
radius_cm = 9.0
wind_interval = 5
ADJUSTMENT = 1.18
interval = 60
gust = 0
def spin():
global wind_count
wind_count = wind_count + 1
def calculate_speed(time_sec):
global wind_count
global gust
circumference_cm = (2 * math.pi) * radius_cm
rotations = wind_count / 2.0
dist_cm = circumference_cm * rotations
dist_km = (circumference_cm * rotations) / 100000
dist_mi = dist_km * 0.621371
mi_per_sec = dist_mi / time_sec
mi_per_hour = mi_per_sec * 3600
return mi_per_hour * ADJUSTMENT
def reset_wind():
global wind_count
wind_count = 0
def reset_gust():
global gust
gust = 0
wind_speed_sensor = Button(16)
wind_speed_sensor.when_activated = spin
while True:
print("Starting Weather Sensor Read Loop...")
start_time = time.time()
while time.time() - start_time <= interval:
print("Start timed loop...")
wind_start_time = time.time()
reset_wind()
reset_gust()
store_speeds = []
time.sleep(wind_interval)
final_speed = calculate_speed(wind_interval)
store_speeds.append(final_speed)
wind_gust_speed = (max(store_speeds))
wind_speed = (statistics.mean(store_speeds))
print(wind_average, wind_speed)
When I comment out "store_speeds = [ ]" the first loop the speeds are reported the same, every loop after I get a "max" reading thats "different" than the mean. This still troubles me, because why on the first loop are they the same? Am I wrong for thinking with the wind_interval set at 5, and the interval set to 60, that its taking 5 second samples over a 60 second period, giving me 12 sample to get the mean and max from?
My goal is every time it reports, I get a mean and max for that "loop" if possible, and not a mean/max over the time the script stays running before its interrupted/stopped.
Here is the working and corrected code:
from gpiozero import Button
import time
import math
import statistics
wind_count = 0
radius_cm = 9.0
wind_interval = 5
interval = 30
CM_IN_A_KM = 100000.0
SECS_IN_AN_HOUR = 3600
ADJUSTMENT = 1.18
store_speeds = []
def reset_wind():
global wind_count
wind_count = 0
def spin():
global wind_count
wind_count = wind_count + 1
def calculate_speed(time_sec):
global wind_count
circumference_cm = (2 * math.pi) * radius_cm
rotations = wind_count / 2.0
dist_km = (circumference_cm * rotations) / CM_IN_A_KM
km_per_sec = dist_km / time_sec
km_per_hour = km_per_sec * SECS_IN_AN_HOUR
mi_per_hour = km_per_hour * 0.6214
return mi_per_hour * ADJUSTMENT
wind_speed_sensor = Button(16)
wind_speed_sensor.when_pressed = spin
while True:
store_speeds = []
for _ in range (interval//wind_interval):
reset_wind()
#reset_gust()
time.sleep(wind_interval) # counter is spinning in background
final_speed = calculate_speed(wind_interval)
store_speeds.append(final_speed)
wind_gust = max(store_speeds)
wind_speed = statistics.mean(store_speeds)
print(wind_speed, wind_gust)

Tektronix MSO56 Oscilloscope: SEVERE Memory Error

I am collecting over 100k FastFrame images (100 frames, with 15k points each), with summary mode and collecting them via python pyvisa using ni-visa.
The error is as follows:
SEVERE
The system is low on memory. Some results may be incomplete. To remedy, reduce record length or remove one or more analytical features such as math, measurements, bus decode or search.
After that, I can disconnect, connect again, send commands which update the window, but cannot query anything.
I suspect it is something to do with a memory leak on MSO56 RAM, or communication queue.
Commands like *RST, CLEAR, LCS, and FACTORY do not fix the error.
import pyvisa
import time
if __name__ == '__main__':
## DEV Signal
rm = pyvisa.ResourceManager()
ll = rm.list_resources()
print('\n\n\n----------------------\nAvailable Resources\n----------------------')
for i in range(len(ll)):
print(F'Resource ID {i}: {ll[i]}')
#i = int(input(F"\n\nPlease select 'Resource ID' from above: "))
i=0;
inst = rm.open_resource(ll[i])
inst.timeout = 10000
reset = inst.write("*RST")
ind = inst.query("*IDN?")
print(F"\nResource {i}: {ind}")
inst.write('C1:OUTP ON')
inst.write('C2:OUTP ON')
# Wave signal
Ch = 1; # channel 1 || 2
wave_name = 'UT1'
Frq = 500000; #Hz
Peri = 1/Frq;# Length of waveform
print(F"Period: {Peri}")
# trigger on channel 2
inst.write(F'C2:BSWV WVTP,SQUARE,FRQ,{Frq},AMP,1,OFST,0,DUTY,1')
# signal on channel 1
inst.write(F'C1:BSWV WVTP,SQUARE,FRQ,{Frq},AMP,1,OFST,0,DUTY,10')
inst = []
scope_ip = '192.168.0.10';
rm = pyvisa.ResourceManager()
ll = rm.list_resources()
print(ll)
for l in ll:
if scope_ip in l:
vScope = rm.open_resource(l)
#vScope.clear()
#vScope.close()
vScope.timeout = 2000
## attempts to fix Memory Error
vScope.write_raw('FPANEL:PRESS RESTART')
vScope.write_raw('*PSC ON')
vScope.write_raw('*CLS')
vScope.write_raw('FACTORY\n')
vScope.write_raw('*RST')
vScope.write_raw('*CLEAR')
vScope.write_raw('*ESE 1')
vScope.write_raw('*SRE 0')
vScope.write_raw('DESE 1')
print('\nESR')
print(vScope.query('*ESR?'))
#print('\nEVMSG?')
#print(vScope.query('*EVMsg?'))
#print(vScope.query('*ESE ?'))
# Display Wave Forms
vScope.write_raw('DISPLAY:WAVEVIEW1:CH1:STATE 1')
vScope.write_raw('DISPLAY:WAVEVIEW1:CH2:STATE 1')
# Vertical Command Groups.
vScope.write_raw('CH1:Coupling DC')
vScope.write_raw('CH2:Coupling DC')
vScope.write_raw('CH1:SCALE .5') # *10 for the range
vScope.write_raw('CH2:SCALE .5')
vScope.write_raw('CH1:Position 0')
vScope.write_raw('CH2:Position 0')
vScope.write_raw('TRIGGER:A:TYPE EDGE')
vScope.write_raw('TRIGGER:A:EDGE:SOURCE CH2')
vScope.write_raw('TRIGger:A:LEVEL:CH2 0')
vScope.write_raw('TRIGger:A:EDGE:SLOpe RISE')
vScope.write_raw('Horizontal:Position 10')
vScope.write_raw('Horizontal:MODE MANUAL')
vScope.write_raw('Horizontal:Samplerate 25000000000')
vScope.write_raw('HORIZONTAL:MODE:RECORDLENGTH 25000')
vScope.write_raw('DATA:SOURCE CH1')
vScope.write_raw('ACQUIRE:STOPAFTER SEQUENCE')## triggers re-read
nframes = 100;
vScope.write_raw(F"HORIZONTAL:FASTFRAME:COUNT {nframes}")
if int(1):
vScope.write_raw(F"DATA:FRAMESTART {1+nframes}")
else:
vScope.write_raw('DATA:FRAMESTART 1')
vScope.write_raw(F"DATA:FRAMESTOP {1+nframes}")
vScope.write_raw('HORIZONTAL:FASTFRAME:STATE OFF')
vScope.write_raw('HORIZONTAL:FASTFRAME:STATE ON')
vScope.write_raw('HORIZONTAL:FASTFRAME:SUMFRAME:STATE ON')
vScope.write_raw(F"HORIZONTAL:FASTFRAME:SELECTED {1+nframes}")
t0 = time.time()
for i in range(1000000):
vScope.write_raw('ACQUIRE:STATE 1') ## triggers re-read
vScope.query('*opc?')
vScope.write_raw(b'WFMOUTPRE?')
wfmo = vScope.read_raw()
vScope.write_raw('CURVE?')
curve = vScope.read_raw()
if i%100 ==0:
print(F"Iteration {i}")
print(F"Time Delta: {time.time()-t0}")
t0=time.time()
Poor Solution.
Restarting the Scope with the power button works.
I should have added that in the question, but takes ~ 2 minutes and is not an elegant solution.

Print Only Seconds for perf_counter()

My code is this:
import time
import winsound
frequency = 2500
duration = 1000
while time.perf_counter() < 5:
print(time.perf_counter())
winsound.Beep(frequency, duration)
How do we only print the seconds?
A naive approach, replace your while loop with:
sec = 0
while time.perf_counter() < 5:
now = max(round(time.perf_counter()), sec)
if now > sec:
sec = now
print(sec)

Polar H10 to RPI Zero W: HR Notifications stop after ca. 100s without error message

I'm using pygatt on a RPI Zero W to access the HR notification stream from a Polar H10 chest belt. The goal is to let an LED blink with the heart rate. Notifications arrive for ca. 100s, then none arrive anymore. No error messages or any (for me recognizable) hint is shown in the debug log.
Any help is greatly appreciated.
The used code is:
from pygatt.util import uuid16_to_uuid
from pygatt.exceptions import NotConnectedError, NotificationTimeout
import binascii
import time
import logging
import RPi.GPIO as gpio
MAC = 'E7:17:FD:20:B1:AA' # MAC address of the Polar H10 belt
HR = 0
RRi1 = 0
RRi2 = 0
LED_On_time = 0.15 # seconds
GPIO_port = 19
gpio.setmode(gpio.BCM)
gpio.setup(GPIO_port, gpio.OUT)
logging.basicConfig(filename='/home/pi/python/debug.log',filemode='w',level=logging.DEBUG)
logging.getLogger('pygatt').setLevel(logging.DEBUG)
def callback(handle, measure):
global HR, RRi1, RRi2
if handle == 16:
for i in range(len(measure)):
if i == 1:
print('Heart rate = ',measure[1],' bpm')
HR = measure[1]
if i == 2:
RRi1 = round((measure[2] + 256*measure[3])/1024,2)
print('RR intervall = %.2f' % RRi1,' s')
if i == 4:
RRi2 = round((measure[4] + 256*measure[5])/1024,2)
print('RR intervall = %.2f' % RRi2,' s')
def Init():
adapter = pygatt.GATTToolBackend()
adapter.start()
try:
""" connect to bluetooth MAC addres with 5 seconds timeout"""
device = adapter.connect(MAC, address_type=pygatt.BLEAddressType.random)
device.bond()
""" generate characteristics uuid's """
uuid_heart_service = uuid16_to_uuid(0x2A37)
""" discover all characteristics uuid's"""
device.discover_characteristics()
device.subscribe(uuid_heart_service, callback, True)
except NotConnectedError:
print('No connection established ')
quit()
Init()
t = time.time() # Initialite with a reasonable value
while(1):
gpio.output(GPIO_port, gpio.HIGH)
time.sleep(LED_On_time)
gpio.output(GPIO_port, gpio.LOW)
time.sleep(max(0, 60/max(HR,30) - (time.time() - t)))
t = time.time()```

Get upload/download kbps speed

I'm using the library called psutil to get system/network stats, but I can only get the total uploaded/downloaded bytes on my script.
What would be the way to natively get the network speed using Python?
If you need to know the transfer rate immediately, you should create a thread that does the calculations continuously. I'm not an expert on the subject, but I tried writing a simple program that does what you need:
import threading
import time
from collections import deque
import psutil
def calc_ul_dl(rate, dt=3, interface="WiFi"):
t0 = time.time()
counter = psutil.net_io_counters(pernic=True)[interface]
tot = (counter.bytes_sent, counter.bytes_recv)
while True:
last_tot = tot
time.sleep(dt)
counter = psutil.net_io_counters(pernic=True)[interface]
t1 = time.time()
tot = (counter.bytes_sent, counter.bytes_recv)
ul, dl = [
(now - last) / (t1 - t0) / 1000.0
for now, last in zip(tot, last_tot)
]
rate.append((ul, dl))
t0 = time.time()
def print_rate(rate):
try:
print("UL: {0:.0f} kB/s / DL: {1:.0f} kB/s".format(*rate[-1]))
except IndexError:
"UL: - kB/s/ DL: - kB/s"
# Create the ul/dl thread and a deque of length 1 to hold the ul/dl- values
transfer_rate = deque(maxlen=1)
t = threading.Thread(target=calc_ul_dl, args=(transfer_rate,))
# The program will exit if there are only daemonic threads left.
t.daemon = True
t.start()
# The rest of your program, emulated by me using a while True loop
while True:
print_rate(transfer_rate)
time.sleep(5)
Here you should set the dt argument to whatever seams reasonable for you. I tried using 3 seconds, and this is my output while runnning an online speedtest:
UL: 2 kB/s / DL: 8 kB/s
UL: 3 kB/s / DL: 45 kB/s
UL: 24 kB/s / DL: 1306 kB/s
UL: 79 kB/s / DL: 4 kB/s
UL: 121 kB/s / DL: 3 kB/s
UL: 116 kB/s / DL: 4 kB/s
UL: 0 kB/s / DL: 0 kB/s
The values seems reasonable since my result from the speedtest were DL: 1258 kB/s and UL: 111 kB/s.
The answer provided by Steinar Lima is correct.
But it can be done without threading also:
import time
import psutil
import os
count = 0
qry = ""
ul = 0.00
dl = 0.00
t0 = time.time()
upload = psutil.net_io_counters(pernic=True)["Wireless Network Connection"][0]
download = psutil.net_io_counters(pernic=True)["Wireless Network Connection"][1]
up_down = (upload, download)
while True:
last_up_down = up_down
upload = psutil.net_io_counters(pernic=True)["Wireless Network Connection"][0]
download = psutil.net_io_counters(pernic=True)["Wireless Network Connection"][1]
t1 = time.time()
up_down = (upload, download)
try:
ul, dl = [
(now - last) / (t1 - t0) / 1024.0
for now, last in zip(up_down, last_up_down)
]
t0 = time.time()
except:
pass
if dl > 0.1 or ul >= 0.1:
time.sleep(0.75)
os.system("cls")
print("UL: {:0.2f} kB/s \n".format(ul) + "DL: {:0.2f} kB/s".format(dl))
v = input()
Simple and easy ;)
I added an LCD mod for this code if you want to test it on a raspberry pi but you need to add the psutil and the lcddriver to your project code!!!!
import time
import psutil
import os
import lcddriver
count=0
qry=''
ul=0.00
dl=0.00
t0 = time.time()
upload=psutil.net_io_counters(pernic=True)['wlan0'][0]
download=psutil.net_io_counters(pernic=True)['wlan0'][1]
up_down=(upload,download)
display = lcddriver.lcd()
while True:
last_up_down = up_down
upload=psutil.net_io_counters(pernic=True)['wlan0'][0]
download=psutil.net_io_counters(pernic=True)['wlan0'][1]
t1 = time.time()
up_down = (upload,download)
try:
ul, dl = [(now - last) / (t1 - t0) / 1024.0
for now,last in zip(up_down, last_up_down)]
t0 = time.time()
#display.lcd_display_string(str(datetime.datetime.now().time()), 1)
except:
pass
if dl>0.1 or ul>=0.1:
time.sleep(0.75)
os.system('cls')
print('UL: {:0.2f} kB/s \n'.format(ul)+'DL:{:0.2f} kB/s'.format(dl))
display.lcd_display_string(str('DL:{:0.2f} KB/s '.format(dl)), 1)
display.lcd_display_string(str('UL:{:0.2f} KB/s '.format(ul)), 2)
# if KeyboardInterrupt: # If there is a KeyboardInterrupt (when you press ctrl+c), exit the program and cleanup
# print("Cleaning up!")
# display.lcd_clear()
v=input()
The (effective) network speed is simply bytes transferred in a given time interval, divided by the length of the interval. Obviously there are different ways to aggregate / average the times and they give you different "measures" ... but it all basically boils down to division.
Another and more simple solution (without threading and queues although still based on #Steinar Lima) and for more recent python:
import time
import psutil
def on_calculate_speed(self, interface):
dt = 1 # I find that dt = 1 is good enough
t0 = time.time()
try:
counter = psutil.net_io_counters(pernic=True)[interface]
except KeyError:
return []
tot = (counter.bytes_sent, counter.bytes_recv)
while True:
last_tot = tot
time.sleep(dt)
try:
counter = psutil.net_io_counters(pernic=True)[interface]
except KeyError:
break
t1 = time.time()
tot = (counter.bytes_sent, counter.bytes_recv)
ul, dl = [
(now - last) / (t1 - t0) / 1000.0
for now, last
in zip(tot, last_tot)
]
return [int(ul), int(dl)]
t0 = time.time()
while SomeCondition:
# "wlp2s0" is usually the default wifi interface for linux, but you
# could use any other interface that you want/have.
interface = "wlp2s0"
result_speed = on_calculate_speed(interface)
if len(result_speed) < 1:
print("Upload: - kB/s/ Download: - kB/s")
else:
ul, dl = result_speed[0], result_speed[1]
print("Upload: {} kB/s / Download: {} kB/s".format(ul, dl))
Or you could also fetch the default interface with pyroute2:
while SomeCondition:
ip = IPDB()
interface = ip.interfaces[ip.routes['default']['oif']]["ifname"]
result_speed = on_calculate_speed(interface)
if len(result_speed) < 1:
print("Upload: - kB/s/ Download: - kB/s")
else:
ul, dl = result_speed[0], result_speed[1]
print("Upload: {} kB/s / Download: {} kB/s".format(ul, dl))
ip.release()
i found this tread, and dont have any idea from python, i jst copy and paste codes, and now need a little help, this script, i have jst show the total of bytes send/recived, can modify to show the actual speed?
def network(iface):
stat = psutil.net_io_counters(pernic=True)[iface]
return "%s: Tx%s, Rx%s" % \
(iface, bytes2human(stat.bytes_sent), bytes2human(stat.bytes_recv))
def stats(device):
# use custom font
font_path = str(Path(__file__).resolve().parent.joinpath('fonts', 'C&C Red Alert [INET].ttf'))
font_path2 = str(Path(__file__).resolve().parent.joinpath('fonts', 'Stockholm.ttf'))
font2 = ImageFont.truetype(font_path, 12)
font3 = ImageFont.truetype(font_path2, 11)
with canvas(device) as draw:
draw.text((0, 0), cpu_usage(), font=font2, fill="white")
if device.height >= 32:
draw.text((0, 14), mem_usage(), font=font2, fill="white")
if device.height >= 64:
draw.text((0, 26), "IP: " + getIP("eth0"), font=font2, fill=255)
try:
draw.text((0, 38), network('eth0'), font=font2, fill="white")
except KeyError:
# no wifi enabled/available
pass
The code
# pip install speedtest-cli
import speedtest
speed_test = speedtest.Speedtest()
def bytes_to_mb(bytes):
KB = 1024 # One Kilobyte is 1024 bytes
MB = KB * 1024 # One MB is 1024 KB
return int(bytes/MB)
download_speed = bytes_to_mb(speed_test.download())
print("Your Download speed is", download_speed, "MB")
upload_speed = bytes_to_mb(speed_test.upload())
print("Your Upload speed is", upload_speed, "MB")
The first answer in interface should be change to desired network adapter. To see the name in ubuntu you can use ifconfig, then change interface='wifi' to the device name.
a little change to formatting in python3
def print_rate(rate):
try:
print(('UL: {0:.0f} kB/s / DL: {1:.0f} kB/s').format(*rate[-1]))
except IndexError:
'UL: - kB/s/ DL: - kB/s'

Categories