Skip to content

Instantly share code, notes, and snippets.

@Ivlyth
Last active September 27, 2019 08:24
Show Gist options
  • Save Ivlyth/4fa77aae9decb5f2b9f0df6178efa825 to your computer and use it in GitHub Desktop.
Save Ivlyth/4fa77aae9decb5f2b9f0df6178efa825 to your computer and use it in GitHub Desktop.
handy function used for cal NIC bandwidth
import psutil
import time
from datetime import datetime
from collections import namedtuple
NicStats = namedtuple('NicStats', ('bytes_recv', 'bytes_sent', 'packets_recv', 'packets_sent', 'dropin', 'dropout'))
def cal_nic_stats(nic_name, duration=1.0, unit_base=1024.0, cycle=10):
def cal():
nic_io_stats1 = psutil.net_io_counters(pernic=True)[nic_name]
time.sleep(duration)
nic_io_stats2 = psutil.net_io_counters(pernic=True)[nic_name]
bytes_recv = (nic_io_stats2.bytes_recv - nic_io_stats1.bytes_recv) * 1.0 / unit_base / unit_base * 8 / duration
bytes_sent = (nic_io_stats2.bytes_sent - nic_io_stats1.bytes_sent) * 1.0 / unit_base / unit_base * 8 / duration
packets_recv = round((nic_io_stats2.packets_recv - nic_io_stats1.packets_recv) * 1.0 / duration, 2)
packets_sent = round((nic_io_stats2.packets_sent - nic_io_stats1.packets_sent) * 1.0 / duration, 2)
dropin = round((nic_io_stats2.dropin - nic_io_stats1.dropin) * 1.0 / duration, 2)
dropout = round((nic_io_stats2.dropout - nic_io_stats1.dropout) * 1.0 / duration, 2)
return NicStats(bytes_recv, bytes_sent, packets_recv, packets_sent, dropin, dropout)
for i in xrange(cycle):
nic_stats = cal()
print '%s - In: %.2fMbps (%.2f pps, %d dropped) Out: %.2fMbps (%.2f pps, %d dropped) Total: %.2fMbps (%.2f pps, %d dropped)' % (
datetime.now().strftime('%H:%M:%S'),
nic_stats.bytes_recv, nic_stats.packets_recv, nic_stats.dropin,
nic_stats.bytes_sent, nic_stats.packets_sent, nic_stats.dropout,
nic_stats.bytes_recv + nic_stats.bytes_sent, nic_stats.packets_recv + nic_stats.packets_sent, nic_stats.dropin + nic_stats.dropout
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment