Skip to main content
 首页 » 编程设计

python每秒平均比特率

2025年05月04日11www_RR

我有一个如下所示的 txt 文件:

0.065998       81    
0.319601      81    
0.539613      81   
0.768445      81   
1.671893      81   
1.785064      81   
1.881242      954   
1.921503      193   
1.921605      188   
1.943166      81   
2.122283      63   
2.127669      83   
2.444705      81   

第一列是数据包到达,第二列是数据包大小(以字节为单位)。

我需要获取每秒字节数的平均值。例如,在第一秒,我只有值为 81 的数据包,因此平均比特率为 81*8= 648bit/s。然后我应该绘制一个图表 x 轴时间(以秒为单位),y 轴平均比特率(每秒)。

到目前为止,我只设法将我的数据作为数组上传:

import numpy as np 
 
d = np.genfromtxt('data.txt') 
 
x = (d[:,0])   
y = (d[:,1 ]) 
 
print x   
print(y*8) 

我是 Python 的新手,所以非常感谢从哪里开始的任何帮助!

这是结果脚本:

import matplotlib.pyplot as plt   
import numpy as np   
x, y = np.loadtxt('data.txt', unpack=True)   
bins = np.arange(60+1)   
totals, edges = np.histogram(x, weights=y, bins=bins)   
counts, edges = np.histogram(x, bins=bins)   
 
print counts   
print totals*0.008/counts   
 
plt.plot(totals*0.008/counts, 'r')   
plt.xlabel('time, s')   
plt.ylabel('kbit/s')   
plt.grid(True)   
plt.xlim(0.0, 60.0)   
plt.show()       

脚本读取包含数据包大小(字节)和到达​​时间的 .txt 文件,并绘制一段时间内的平均比特率/秒。用于监控服务器传入/传出流量!

请您参考如下方法:

您的数据已经按时间排序,所以我可能只对这个使用 itertools.groupby:

from itertools import groupby 
with open('data.txt') as d: 
     data = ([float(x) for x in line.split()] for line in d) 
     for i_time,packet_info in groupby(data,key=lambda x:int(x[0])): 
         print i_time, sum(x[1] for x in packet_info) 

输出是:

0 324.0 
1 1578.0 
2 227.0