python matplotlib 实时绘制iperf吞吐量数据
效果展示
单条流
多条流
python 代码
import sys
import matplotlib.pyplot as plt
import numpy as np
import time
import thread
from matplotlib import animation
colors = ["red",
"green",
"blue",
"rosybrown",
"black"]
markers = ["x",
"o",
"v",
"s",
"*",
]
tp_pair = []
pair_idx = []
pair_cnt = 0
filter_str = "Mbits"
fig = plt.figure(figsize=(18, 8), facecolor="white")
plt.grid(True)
plt.ion()
class tp_item(object):
idx = 0
ts = 0.0
mb = 0.0
bw = 0
def tp_init(self, line):
line = line.strip()
line = line.split()
self.idx = int(line[1].replace("]", ""))
self.ts = float(line[2].split("-")[1])
self.mb = float(line[4])
self.bw = float(line[6])
if self.idx not in pair_idx:
pair_idx.append(self.idx)
update_tp(self.idx, self.ts, self.bw)
def __init__(self, line):
self.tp_init(line)
def update_tp(idx, ts, bw):
i = pair_idx.index(idx)
tp_pair[i][0] = tp_pair[i][1]
tp_pair[i][1] = ts
tp_pair[i][2] = tp_pair[i][3]
tp_pair[i][3] = bw
def dump_tp_item(i):
print("id: %d, ts: %f, MBytes: %f, BW: %f"%(
i.idx, i.ts, i.mb, i.bw))
def tp_graph(f):
cur_base = 0.0
prev_base = 0.0
while True:
try:
while cur_base == prev_base:
l = f.readline()
if (filter_str in l) and ("SUM" not in l):
item = tp_item(l)
dump_tp_item(item)
if (cur_base == 0.0 and prev_base == 0.0):
prev_base = cur_base = item.ts
else:
prev_base = cur_base
cur_base = item.ts
for i in range(len(pair_idx)):
plt.plot([tp_pair[i][0], tp_pair[i][1]], [tp_pair[i][2], tp_pair[i][3]],
color=colors[i], marker=markers[i])
plt.text(tp_pair[i][1], tp_pair[i][3], tp_pair[i][3], ha="center", va="bottom", fontsize=15)
plt.pause(1)
prev_base = cur_base
except Exception as err:
print(err)
def gen_tp_pair(num):
for i in range(num):
tp_pair.append([])
for j in range(4):
tp_pair[i].append(0)
if __name__ == '__main__':
pair_num = 1
if len(sys.argv) < 3:
print("Usage: iperf_tp.py <file path> <flow num>")
exit(-1)
pair_num = int(sys.argv[2])
pair_cnt = pair_num
gen_tp_pair(pair_num)
print(tp_pair)
f = open(sys.argv[1], mode='r')
print("Open: %s"%(sys.argv[1]))
tp_graph(f)
f.close()