如何知道给定时间使用的网络带宽?

时间:2011-12-28 15:02:38

标签: c# performancecounter performance-testing

我正在尝试为在2个不同服务器上运行的程序构建负载均衡器。

到目前为止,我的负载均衡器仅使用每个服务器程序中的PerformanceCounter实例检查每个服务器的CPU使用情况。

我还想检查每台服务器的带宽使用情况,我该如何检查?

(可能也是使用PerformanceCounter完成但我对它的用法不熟悉)

1 个答案:

答案 0 :(得分:21)

感谢月光,我发现了这个http://www.keyvan.ms/how-to-calculate-network-utilization-in-net

public double getNetworkUtilization(string networkCard){

            const int numberOfIterations = 10;

            PerformanceCounter bandwidthCounter = new PerformanceCounter("Network Interface", "Current Bandwidth", networkCard);
            float bandwidth = bandwidthCounter.NextValue();//valor fixo 10Mb/100Mn/

            PerformanceCounter dataSentCounter = new PerformanceCounter("Network Interface", "Bytes Sent/sec", networkCard);

            PerformanceCounter dataReceivedCounter = new PerformanceCounter("Network Interface", "Bytes Received/sec", networkCard);

            float sendSum = 0;
            float receiveSum = 0;

            for (int index = 0; index < numberOfIterations; index++)
            {
                sendSum += dataSentCounter.NextValue();
                receiveSum += dataReceivedCounter.NextValue();
            }
            float dataSent = sendSum;
            float dataReceived = receiveSum;


            double utilization = (8 * (dataSent + dataReceived)) / (bandwidth * numberOfIterations) * 100;
            return utilization;
        }

找到这段代码帮助我的可用网卡:

public void printNetworkCards()
        {
            PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");
            String[] instancename = category.GetInstanceNames();

            foreach (string name in instancename)
            {
                Console.WriteLine(name);
            }
        }