Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does "for" in .Net Framework 4.0 execute loops in parallel? Or why is the total not the sum of the parts

Tags:

c#

.net-4.0

I am writing code to performance test a web site. I have the following code:

        string url = "http://xxxxxx";
        System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();

        System.Diagnostics.Stopwatch totalTime = new System.Diagnostics.Stopwatch();
        totalTime.Start();

        for (int i = 0; i < 10; i++)
        {
            stopwatch.Start();
            WebRequest request = HttpWebRequest.Create(url);
            WebResponse webResponse = request.GetResponse();
            webResponse.Close();
            stopwatch.Stop();
            textBox1.Text += "Time Taken " + i.ToString() + " = " + stopwatch.Elapsed.Milliseconds.ToString() + Environment.NewLine;
            stopwatch.Reset();

        }

        totalTime.Stop();
        textBox1.Text += "Total Time Taken = " + totalTime.Elapsed.Milliseconds.ToString() + Environment.NewLine;

Which is giving the following result:

Time Taken 0 = 88
Time Taken 1 = 161
Time Taken 2 = 218
Time Taken 3 = 417
Time Taken 4 = 236
Time Taken 5 = 217
Time Taken 6 = 217
Time Taken 7 = 218
Time Taken 8 = 409
Time Taken 9 = 48
Total Time Taken = 257

I had expected the total time to be the sum of the individual times. Can anybody see why it is not?

like image 888
Shiraz Bhaiji Avatar asked Dec 05 '22 03:12

Shiraz Bhaiji


1 Answers

Use TotalMilliseconds instead of Milliseconds and try your test again. Your results aren't what you think they are.

like image 59
David Morton Avatar answered Jan 20 '23 07:01

David Morton