Question:
The code performs 10 operations:
var start = DateTime.Now;
Foo();
var end = DateTime.Now;
Task: add up the end – start difference of all 10 operations and get the average value
I did this, but the results are obviously wrong:
var time = result.Aggregate(time, (current, finalResult) => current + (end - start));
Console.WriteLine(new DateTime(time.Ticks / Count).ToString("mm:ss.fff"));
Answer:
You should use Stopwwatch instead of DateTime. Stopwatch is just designed to accurately measure time intervals, in particular, the execution time of code sections. Firstly, it has a higher resolution than DateTime (DateTime will not be able to correctly measure short intervals of the order of one millisecond or less), and secondly, even theoretically, it is possible that some kind of correction of the system time, which is fraught with incorrect measurement (say, there will be a time translation). Plus, it is easier to operate with milliseconds and ticks of the system timer than with dates and TimeSpans.
To solve your problem, do it in the simplest way – measure the code execution time in milliseconds or ticks 10 times, add and divide by 10, elementary arithmetic