测量服务器带宽

测量服务器带宽

我想测量用 Python 实现的邮件转发服务器的带宽,这意味着我想测量我的服务器每秒处理的字节数。因此,我计划这样做:在一段固定的时间内(例如300sec),我测量received bytes和的数量sent bytes。在这段时间之后,我计算比率:bytes_received / bytes_sent。但是,我不确定这是否是我想要的,因为它给了我一个比率(通常在 1-1.5 左右),所以这意味着我处理了在某个时间段内收到的所有或几乎所有消息,但我想测量我处理了多少字节。如果有人能建议我如何测量带宽,我将不胜感激。

答案1

我认为你需要这样做:

已接收字节数= 已接收字节数 300 秒 - 已接收字节数 0 秒

已发送字节数= 已发送 300 字节数 - 已发送 0 字节数

已处理的总字节数= 接收字节数 - 发送字节数

这将为您提供 300 秒内处理的总字节数。

答案2

您可以使用 psutil.net_io_counters() 来计算一段时间内的带宽。您将在 0 秒时拍摄快照,并在 300 秒时拍摄快照。

def get_bandwidth():
    # Get net in/out
    net1_out = psutil.net_io_counters().bytes_sent
    net1_in = psutil.net_io_counters().bytes_recv

    time.sleep(300) # Not best way to handle getting a value 300 seconds later

    # Get new net in/out
    net2_out = psutil.net_io_counters().bytes_sent
    net2_in = psutil.net_io_counters().bytes_recv

    # Compare and get current speed
    if net1_in > net2_in:
        current_in = 0
    else:
        current_in = net2_in - net1_in

    if net1_out > net2_out:
        current_out = 0
    else:
        current_out = net2_out - net1_out

    network = {"traffic_in": current_in, "traffic_out": current_out}

    # Return data in bytes
    return network

相关内容