Slow while loop in C #

I have a loop while, and all it does is call the method. I have a timer outside the loop and another timer that gradually increases the time the method is called inside the loop. External time takes about 17 seconds, and the total value of the internal timer is 40 ms. The cycle runs 50,000 times. Here is a sample 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 greatly appreciated. Massimo

+5
source share
7 answers

You are comparing apples and oranges. Your external timer measures the total time. Your internal timer measures the number of whole milliseconds received by the call on Method1.

ElapsedMilliseconds , ." , 50 000 .

Method1 1 , ElapsedMilliseconds 0, , . , 0,3 , , 1 40 .

Elapsed.TotalMilliseconds ElapsedTicks ElapsedMilliseconds. 10 000 .

+8

: TestCollection.Count?

, 17 50 000 .

+2

:

while (count <= TestCollection.Count) {
...
}

:

int total = TestCollection.Count;
while (count <= total) {
...
}
+1

, , # ,

TestCollection.Count

. .

.

, , - Array.Length, . " " .

+1

, , Ticks

:

long InnerTime = 0;
long OutterTime = 0;

Stopwatch Stopw1 = new Stopwatch();
Stopwatch Stopw2 = new Stopwatch();

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

. , :

long innertime = 0;

while (count <= TestCollection.Count) 
{     
    innertime -= Stopw2.GetTimestamp();
    Medthod1();
    innertime += Stopw2.GetTimestamp();
    count++; 
} 

Console.WriteLine("{0} ms", innertime * 1000.0 / Stopw2.Frequency);
0
source

Since you started with int count = 1;, if your loop executes 50,000 times, that means the value TestCollection.Countis 50,000. Thus, your code needs to compute that value 50,000 out of TestCollection.Count50,000 times, once per loop input,
Thus, depending on of what it really does Medthod1(), time may be normal. Store the value TestCollection.Countin a variable and compare the loop counter with this.

0
source

All Articles