如何测量C# NetworkStream.Read所花费的时间?
我想测量客户端使用 C# 通过 tcp 接收数据所花费的时间。
我使用 NetworkStream.Read 读取使用 NetworkStream.Write 发送的 100 兆数据。我将缓冲区设置为与数据大小相同,因此不存在缓冲区欠载问题等。通常看起来像这样。
Stopwatch sw = new Stopwatch();
sw.Start();
stream.Read(bytes, 0, bytes.Length);
sw.Stop();
问题是,有可能发送者还没有真正发送数据,但秒表已经在运行。如何准确测量接收数据所需的时间?我确实尝试过利用远程pc流的延时进行写入,但是写入所花费的时间极少。 顺便问一下,秒表是完成这项任务最准确的工具吗?
I want to measure time taken for client to receive data over tcp using c#.
Im using NetworkStream.Read to read 100 megabits of data that are sent using NetworkStream.Write. I set the buffer to the same size of data, so there no buffer underrun problem etc. Generally it looks like this.
Stopwatch sw = new Stopwatch();
sw.Start();
stream.Read(bytes, 0, bytes.Length);
sw.Stop();
The problem is, there is a possibility where the sender hasnt actually sent the data but the stopwatch is already running. how can i accurately measure the time taken to receive the data? i did try to use the time lapse of the remote pc stream.Write, but the time it took to write is extremely small.
by the way, is the stopwatch is the most accurate tool for this task?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以采取的一种方法是开始读取数据并根据事件处理中数据的可用性启动秒表。注册一个事件,当数据可用时将触发该事件。但这需要仔细的设计方法,例如丢弃初始和最终不需要的数据。
One approach you could take is to start reading the data and start the stopwatch depending on availability of data through event handling. Register an event that will be fired when data will be available. This would require careful design approach though, such as discarding initial and final unneeded data.
NetworkStream 中没有事件表明数据可用。您拥有的只是 DataAvailable 属性你可以用来投票。例如,
There are no events in NetworkStream to indicate data is available. All you have is DataAvailable property that you can used to poll. For example,