Skip to content

Instantly share code, notes, and snippets.

@cbruegg
Created November 4, 2016 13:19
Show Gist options
  • Save cbruegg/340ab29bbf6d68c6340658b928d6abc6 to your computer and use it in GitHub Desktop.
Save cbruegg/340ab29bbf6d68c6340658b928d6abc6 to your computer and use it in GitHub Desktop.
import psutil
import time
import collections
###
### Simply pipe the output of this program into a file
### to obtain CSV formatted data about the CPU, memory,
### network and disk. Press CTRL-C to stop writing.
###
SAMPLE_IOPS_TIME_SECS = 2
DiskIOPS = collections.namedtuple('DiskIOPS', 'read_ops_per_sec write_ops_per_sec')
NetIOPS = collections.namedtuple('NetIOPS', 'recv_packets_per_sec sent_packets_per_sec')
def disk_iops():
start = psutil.disk_io_counters()
time.sleep(SAMPLE_IOPS_TIME_SECS)
end = psutil.disk_io_counters()
reads = end.read_count - start.read_count
writes = end.write_count - start.write_count
return DiskIOPS(read_ops_per_sec = reads / SAMPLE_IOPS_TIME_SECS, write_ops_per_sec = writes / SAMPLE_IOPS_TIME_SECS)
def net_iops():
start = psutil.net_io_counters()
time.sleep(SAMPLE_IOPS_TIME_SECS)
end = psutil.net_io_counters()
recv = end.packets_recv - start.packets_recv
sent = end.packets_sent - start.packets_sent
return NetIOPS(recv_packets_per_sec = recv / SAMPLE_IOPS_TIME_SECS, sent_packets_per_sec = sent / SAMPLE_IOPS_TIME_SECS)
def csv_header():
header = ""
for i in range(psutil.cpu_count()):
header += ("cpu_load_percent" + str(i) + ",")
header += "mem_usage_percent,disk_read_ops_per_sec,disk_write_ops_per_sec,"
header += "net_recv_packets_per_sec,net_sent_packets_per_sec"
return header
def csv_row():
row = ""
for cpu_percent in psutil.cpu_percent(percpu=True):
row += str(cpu_percent) + ","
row += str(psutil.virtual_memory().percent) + ","
row += str(psutil.virtual_memory().percent) + ","
diops = disk_iops()
niops = net_iops()
row += str(diops.read_ops_per_sec) + ","
row += str(diops.write_ops_per_sec) + ","
row += str(niops.recv_packets_per_sec) + ","
row += str(niops.sent_packets_per_sec)
return row
print(csv_header())
while True:
print(csv_row())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment