Was it time to start and stop the stopwatch?

I have a very specific question that I need to answer for a very specific performance test. I will simplify the code to make it more understandable.

I do a lot of calculations (several tens of millions), everything is done in cycles that are themselves not too long, and I need the total calculation time. However, all calculations are not performed directly one after another, and the additional code โ€œenters the gapโ€ of each cycle.

What I need is a completely accurate total time of all cycles (including declaring and initializing i, increasing it and comparing it with 100 in exmaple). To measure time, I start Stopwatch just before each cycle and stop it immediately after the cycle. But do these two actions take some time, which can make a difference?

Example:

 Stopwatch sw = new Stopwatch(); sw.Start(); //how long does it now take until for loop is reached? for(int i = 0; i < 100; i++) { //some calculations } //how much time does it take to stop sw? sw.Stop(); 

Of course, it would not matter if all the loops were executed directly one after another, I could only start at the beginning of the first cycle and stop at the end of the last, but this is impossible.

I know that the question is very specific, but I hope someone can help me here, since a considerable time coming from about fifty million cycles can somehow affect my results.

+4
source share
2 answers

Well, you could try this and test it yourself, on my (lousy executing) computer - about 0.0006 milliseconds for the first execution and 0.0001 milliseconds for the next executions. Try it yourself:

 Stopwatch sw = new Stopwatch(); sw.Start(); sw.Stop(); TimeSpan ts = TimeSpan.FromTicks(sw.ElapsedTicks); string elapsed = ts.TotalMilliseconds.ToString(); 
+2
source

What I need is the exact time of all the cycles. To measure time, I start StopWatch just before each cycle and stop it right after the cycle. But do these two actions take some time, which can make a difference?

They take some time - like initializing i , and incrementing, and comparing with 100 in each iteration of the loop. Almost nothing happens instantly when calculating.

Whether this is relevant or not is another matter. If your calculation is not trivial, it is unlikely that it will be significant in your time. You can try to synchronize an empty loop, but it is possible that the JIT compiler will completely get rid of the loop.

+4
source

Source: https://habr.com/ru/post/1446806/


All Articles