Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slow While loop in C#

I have a while loop and all it does is a method call. I have a timer on the outside of the loop and another timer that incrementally adds up the time the method call takes inside the loop. The outer time takes about 17 seconds and the total on the inner timer is 40 ms. The loop is executing 50,000 times. Here is an example of the code:

long InnerTime = 0;
long OutterTime = 0;
Stopw1.Start();
int count = 1;
while (count <= TestCollection.Count) {
    Stopw2.Start();
    Medthod1();
    Stopw2.Stop();
    InnerTime = InnerTime + Stopw2.ElapsedMilliseconds;
    Stopw2.Reset();
    count++;
}
Stopw1.Stop();
OutterTime = Stopw1.ElapsedMilliseconds;
Stopw1.Reset();

Any help would be much appreciated. Massimo

like image 812
Massimo Guerrera Avatar asked Jul 19 '12 17:07

Massimo Guerrera


People also ask

How do you slow down a while loop?

You would do this using the Interval property. timer2. Interval = 1000; //This would make the timer tick every second.

Which is fast for or while loop in C?

Using for: % Time elapsed: 0.0010001659 seconds. Using while: % Time elapsed: 0.026000023 seconds. The main reason that While is much slower is because the while loop checks the condition after each iteration, so if you are going to write this code, just use a for loop instead.

Which loop in C is faster in execution?

"Do-While loop is the fastest loop in C programming".

Why is my for loop taking so long?

Growing variables in a loop takes very long. Each time you increase the length of the variable, a million times here, you force MATLAB to first create a variable with the initial length+1, then copy the contents, then delete the old variable. That's probably what is taking your code so long.


2 Answers

You are comparing apples and oranges. Your outer timer measures the total time taken. Your inner timer measures the number of whole milliseconds taken by the call to Method1.

The ElapsedMilliseconds property "represents elapsed time rounded down to the nearest whole millisecond value." So, you are rounding down to the nearest millisecond about 50,000 times.

If your call to Method1 takes, on average, less than 1ms, then most of the time, the `ElapsedMilliseconds' property will return 0 and your inner count will be much, much less than the actual time. In fact, your method takes about 0.3ms on average, so you're lucky even to get it to go over 1ms 40 times.

Use the Elapsed.TotalMilliseconds or ElapsedTicks property instead of ElapsedMilliseconds. One millisecond is equivalent to 10,000 ticks.

like image 161
Jeffrey Sax Avatar answered Sep 28 '22 06:09

Jeffrey Sax


What is this doing: TestCollection.Count ?

I suspect your 17 seconds are being spent counting your 50,000 items over and over again.

like image 33
Chris Dickson Avatar answered Sep 28 '22 06:09

Chris Dickson