Wednesday, November 6, 2019

How to Calculate Estimated Time Left in C# for Time-Consuming Process



I can suggest my today's discovery for estimating the seconds left in a 3 minutes process in C#.
Anyone better approach?

            Stopwatch sw;
            long totaltime = 0; // counts the total time passed in milliseconds
            int secondsleft; // estimated time left
            int i = 0; // counter in the foreach loop
            // objList has couple of hundred elements
            //secondsleft is recalculated after each iteration

            foreach (var obj in objList)
            {
                sw = Stopwatch.StartNew();
                //some time consuming process here
                i++;
                totaltime = totaltime + sw.ElapsedMilliseconds;
                secondsleft = (int) Math.Floor((double) totaltime / i / 1000 * (objList.Count() - i));
            }

No comments:

Post a Comment