DEV Community

Zoltan Halasz
Zoltan Halasz

Posted on

Estimated Time Left Calculation in C#

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));
            }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)