c#计算网络速度

本文介绍了一个用于实时监测网络传输速度的C#类。该类通过记录一段时间内的数据传输量来计算平均传输速率,并能根据不同时间间隔调整监测精度。文章详细展示了如何实现数据包大小和时间戳的记录,以及如何计算和更新显示当前的网络传输速度。
    public sealed class NetworkSpeed
    {
        private struct Speed
        {
            public DateTime Time;
            public long Size;
        }

        List<Speed> SpeedList = new List<Speed>();

        public void Increment(long value)
        {
            lock (this)
            {
                SpeedList.Add(new Speed() { Size = value, Time = DateTime.Now });
                if (this.SpeedList.Count > 3000)
                {
                    if (this.SpeedList.Count > 0)
                    {
                        this.SpeedList.RemoveAt(0);
                    }
                }
            }
        }

        DateTime LastGetSpeedTime = DateTime.Now;

        unsafe public string GetSpeed()
        {
            lock (this)
            {
                if (this.SpeedList.Count > 0 && DateTime.Now.Subtract(this.SpeedList[this.SpeedList.Count - 1].Time).TotalSeconds > 1)
                {
                    this.SpeedList.Clear();
                    this.LastGetSpeedTime = DateTime.Now;
                }
                this.LastGetSpeedTime = DateTime.Now;
                if (this.SpeedList.Count == 0) return "0 B/s";
                long total = 0;
                for (int i = 0; i < this.SpeedList.Count; i++)
                {
                    total += this.SpeedList[i].Size;
                }
                double speed = total / (DateTime.Now - this.SpeedList[0].Time).TotalSeconds;
                return string.Format("{0}/s", GetText(speed));
            }
        }

        private string GetText(double size)
        {
            if (size < 1024)
                return string.Format("{0} B", size.ToString("0.0"));
            else if (size < 1024 * 1024)
                return string.Format("{0} KB", (size / 1024.0f).ToString("0.0"));
            else
                return string.Format("{0} MB", (size / (1024.0f * 1024.0f)).ToString("0.0"));
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值