Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the average TimeSpan between a collection of DateTimes

Tags:

c#

linq

.net-4.0

Let's say we're tracking the times when a user is performing a certain action, and we want to know the average time between said actions.

For example, if the user performed this action at these times:

  • today, 1 PM
  • today, 3 PM
  • today, 6 PM

The result would be 2.5 hours.

I actually have solved this already, but I felt my solution was more complicated than necessary. I'll post it as an answer.

like image 298
adamjford Avatar asked May 27 '11 18:05

adamjford


2 Answers

It seems that you are basically looking for Max - Min divided by Count.

    public TimeSpan? Average
    {
        get
        {
            var diff = _dateTimes.Max().Subtract(_dateTimes.Min());
            var avgTs = TimeSpan.FromMilliseconds(diff.TotalMilliseconds / (_dateTimes.Count() - 1));
            return avgTs;
        }
    }

Make sure you check that there is more than one DateTime.

Update: Even more accurate if you use Ticks.

TimeSpan.FromTicks(diff.Ticks / (_dateTimes.Count() - 1));
like image 125
tofutim Avatar answered Sep 18 '22 15:09

tofutim


I recently had a similar task in where I had a long running operation iterating over thousands of rows with 20-30 iterations within each.

 void LongRunningOperation()
    {
        int r = 5000;
        int sR = 20;
        List<TimeSpan> timeSpanList = new List<TimeSpan>();
        for (int i = 0; i < r; i++)
        {

            DateTime n = DateTime.Now; // Gets start time of this iteration.
            for (int x = 0; x < sR; x++)
            {
                 // DOING WORK HERE       
            }
            timeSpanList.Add(DateTime.Now - n); // Gets the length of time of iteration and adds it to list.
            double avg = timeSpanList.Select(x => x.TotalSeconds).Average(); // Use LINQ to get an average of the TimeSpan durations.
            TimeSpan timeRemaining = DateTime.Now.AddSeconds((r - i) * avg) - DateTime.Now;
            // Calculate time remaining by taking the total number of rows minus the number of rows done multiplied by the average duration.
            UpdateStatusLabel(timeRemaining);
        }
    }
like image 26
Jordan Fulford Avatar answered Sep 22 '22 15:09

Jordan Fulford