Python每秒平均比特率

1 投票
3 回答
2531 浏览
提问于 2025-04-17 14:27

我有一个 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 文件,里面包含了数据包的大小(字节)和到达时间,并绘制了在一段时间内的平均比特率/秒。这个脚本可以用来监控服务器的进出流量!

3 个回答

0

由于到达时间不规律,我建议把这些时间转换成整数秒,然后把每秒钟所有到达的数据总量加起来。这样做之后,绘图和其他分析就简单多了。

5

你的数据已经按照时间排序了,所以我可能会用 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
4

如果你想使用 numpy,可以用 numpy.histogram 这个工具:

>>> import numpy as np
>>> x, y = np.loadtxt('data.txt', unpack=True)
>>> bins = np.arange(10+1)
>>> totals, edges = np.histogram(x, weights=y, bins=bins)
>>> totals
array([  324.,  1578.,   227.,     0.,     0.,     0.,     0.,     0.,
           0.,     0.])

这个工具会给出每个区间(也叫“箱子”)里的总数,你可以把这个总数除以区间的宽度,来得到一个大致的瞬时速率:

>>> totals/np.diff(bins)
array([  324.,  1578.,   227.,     0.,     0.,     0.,     0.,     0.,
           0.,     0.])

(好吧,因为这些区间的宽度都是1,所以这个结果其实没什么特别的。)

[更新]

我不太明白你后面提到的需要每秒的平均数据包大小 -- 我在你的问题里没看到这个内容,但我确实有错过明显信息的名声.. :-/ 不管怎样,如果你想知道每个时间区间里的数据包数量,那你其实不需要设置权重(默认就是1):

>>> counts, edges = np.histogram(x, bins=bins)
>>> counts
array([4, 6, 3, 0, 0, 0, 0, 0, 0, 0])

这里的 counts 就是每个区间里到达的数据包数量。

撰写回答