Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to estimate end time of method in WinForms to properly inform user about predicted time of finish?

I've got some timers that measure the time to execute code.

 DateTime startTimeFunctionTotal = DateTime.Now;
     for (int i = 0; i < array.Count; i++) {
         DateTime startTimeFunction = DateTime.Now;
         //some code here

          DateTime stopTimeFunction = DateTime.Now;
          TimeSpan durationTimeFunction = stopTimeFunction - startTimeFunction ;

 }
 DateTime stopTimeFunctionTotal = DateTime.Now;
 TimeSpan durationTimeFunctionTotal = stopTimeFunctionTotal - startTimeFunctionTotal ;

It's allowed (even better) if the predicted time changes according to more data (every loop there is more data so prediction should be more accurate).

I would like to give user a predicted time of finish (both time like 15 minutes, and 10:56).

like image 917
MadBoy Avatar asked Mar 01 '10 16:03

MadBoy


People also ask

How do I stop a method execution in C#?

Use the continue Statement to Exit a Function in C# The continue statement skips the execution of a block of code when a certain condition is true. Unlike the break statement, the continue statement transfers the control to the beginning of the loop. Below is an example of code using a foreach method.


1 Answers

Assuming each action in your for statement takes roughly the same amount of time:

List<TimeSpan> timeSpans = new List<TimeSpan>();
for(int i = 0; i < array.Count; i++)
{
    Stopwatch watch = Stopwatch.StartNew();
    //do stuff
    timeSpans.Add(watch.Elapsed);
    long ticksLeft = timeSpans.Sum(ts => ts.Ticks) * (array.Count - i) / timeSpans.Count;
    Console.WriteLine("Left: " + new TimeSpan(ticksLeft));
    Console.WriteLine("Finished in: " + 
        DateTime.Now.AddTicks(ticksLeft));
}

To go with the median use:

long ticksLeft = timeSpans.OrderBy(ts => ts.Ticks)
    .ElementAt(timeSpans.Count / 2).Ticks * (array.Count - i);
like image 182
Yuriy Faktorovich Avatar answered Oct 09 '22 08:10

Yuriy Faktorovich