问题
I'm using HttpClient to post a byte array to a server. How can I tell how many bytes are transferred per second?
回答1:
The simplest, naive way to do it is to use the Stopwatch
class to get the interval before and after your HttpClient.PostAsync
call, then divide that time by the payload size:
byte[] payload = GetData();
var content = new ByteArrayContent(payload);
var stopwatch = Stopwatch.Start();
await httpClient.PostAsync(url, content);
stopwatch.Stop();
var bps = payload.Length / stopwatch.Elapsed.TotalSeconds;
This is a primitive method, because it doesn't count how long it took for the actual bytes to make it through the network interface, but the total, inclusive time it took the HttpClient class to perform the POST operation - including allocating memory, spinning up threads if necessary, the mechanics of the async/await operations and so on. However, in most cases, these are all noticeably faster than the actual I/O, so it might be negligible - it depends on how accurate you need your results.
A more accurate way can be done using the NetworkInterface class to check the BytesSent counter, which can be found here:
- How to get accurate download/upload speed in C#.NET?
来源:https://stackoverflow.com/questions/50886000/how-can-i-get-my-upload-speed-with-httpclient