Calculate Time Remaining

后端 未结 16 2650
一生所求
一生所求 2020-12-04 08:22

What\'s a good algorithm for determining the remaining time for something to complete? I know how many total lines there are, and how many have completed already, how shoul

16条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 09:09

    There is 2 ways of showing time

    1. Time elapsed and Time Remaining overall: so elapsed will increase but remaining will be likely stable total time needed (if per second is stable)

    2. Time elapsed and Time Left:
      so Time Left = Total Needed - Elapsed

    My idea/formula is more likely like this:

    Processed - updated from running thread from 0 to Total

    I have timer with 1000ms interval that calculates processed per second:

    processedPerSecond = Processed - lastTickProcessed;
    lastTickProcessed = Processed;  //store state from past call
    

    processedPerSecond and lastTickProcessed are global variables out of timer method

    Now if we would like to get how many seconds is required to complete the processing (in ideal constant assumption) totalSecondsNeeded = TotalLines / PerSecond

    but we want to show case 2. TimeLeft so TimeLeftSeconds = (TotalLines - Processed) / PerSecond

    TimeSpan remaining = new TimeSpan(0, 0, (transactions.Count - Processed) / processedPerSecond);
    labelTimeRemaining.Text = remaining.ToString(@"hh\:mm\:ss");
    

    Of course TimeLeftSeconds will "jump" if PerSecond jumps, so if past PerSecond was 10 then 30 then back to 10, the user will see it.

    There is a way to calculate average, but this may not show real time left if process speeds up at the end

    int perSecond = (int)Math.Ceiling((processed / (decimal)timeElapsed.TotalSeconds));  //average not in past second
    

    So it may be the choice for a developer to "pick" a method that will be most accurate based on prediction of how "jumpy" the processing is

    We could also calculate and save each PerSecond, then take last 10 second and made average, but in this case user will have to wait 10 seconds to see first calculation or we could show time left starting from first per second and then progressively average summing up to 10 last PerSecond

    I hope my "jumpy" thoughts will help someone to build something satisfying

提交回复
热议问题