如何测量C# NetworkStream.Read所花费的时间?

发布于 2024-10-10 05:46:05 字数 376 浏览 0 评论 0原文

我想测量客户端使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

难如初 2024-10-17 05:46:05

您可以采取的一种方法是开始读取数据并根据事件处理中数据的可用性启动秒表。注册一个事件,当数据可用时将触发该事件。但这需要仔细的设计方法,例如丢弃初始和最终不需要的数据。

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.

极致的悲 2024-10-17 05:46:05

NetworkStream 中没有事件表明数据可用。您拥有的只是 DataAvailable 属性你可以用来投票。例如,

do {
  // sleep for some time
}
while(stream.DataAvailable);
Stopwatch sw = new Stopwatch();
sw.Start();
stream.Read(bytes, 0, bytes.Length);
sw.Stop();

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,

do {
  // sleep for some time
}
while(stream.DataAvailable);
Stopwatch sw = new Stopwatch();
sw.Start();
stream.Read(bytes, 0, bytes.Length);
sw.Stop();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文