I'm writing a speed test in C# that essentially connects to a server and downloads a certain amount of bytes and then repeats over 2 seconds measuring the time it takes for each, then finds the average time taken. I'm almost positive that the dns query to the server is not included in timing, but if someone could verify that for me, I would greatly appreciate it.
Code:
int bsize = 8192;
byte[] inbuffer = new byte[bsize]; //create byte-array of size 8192 bytes
TcpClient Client = new TcpClient();
//I believe that this is where the DNS query is happening, and the timer hasn't started yet.
Client.Connect("host.ca", 10001); //connect to the server on port 10001 (for reading)
NetworkStream Stream = Client.GetStream();
double tread = 0;
double tcp = 0;
double read = 0;
TimeSpan elapsed = new TimeSpan();
Stopwatch sw = Stopwatch.StartNew(); //used to time
while(true) //this repeats until elapsed = 2 seconds, and then it breaks
{
elapsed = sw.Elapsed;
try
{
read = Stream.Read(inbuffer, 0, bsize);
}
catch
{
return "Could not get download speed. Read failed.";
}
tread += read;
if (elapsed.Seconds > 2)
{
sw.Stop();
double rspeed = (8 * tread) / (elapsed.Seconds * 1024 * 1024);
tcp = (double)Math.Round(rspeed, 2);
break;
}
}
I'm also interested to hear if anyone has criticisms about my code (I'm here to learn), or if there is a more efficient (in terms of accuracy, time, or precision) way of doing a speed test.
Thanks for any help guys.
Comments
Post a Comment