Calculate the average TimeSpan between the DateTimes collection

Let's say we track the time when the user performs a specific action, and we want to know the average time between the specified actions.

For example, if the user performed this action at this time:

  • today, 1 pm
  • today, 3 hours.
  • today, 6 pm

The result will be 2.5 hours.

I really decided it already, but I felt that my decision was more complicated than necessary. I will send it as an answer.

+4
source share
3 answers

It seems that you are mostly 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 that you check that there is more than one time period.

Update: More precisely, if you use Ticks.

 TimeSpan.FromTicks(diff.Ticks / (_dateTimes.Count() - 1)); 
+5
source

Recently I had a similar task in which I had a long work, iterating over thousands of lines with 20-30 iterations inside 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); } } 
+3
source

Here's how I solved it, but I don't like it:

 public class HistoryItem { private IEnumerable<DateTime> _dateTimes; public TimeSpan? Average { get { TimeSpan total = default(TimeSpan); DateTime? previous = null; int quotient = 0; var sortedDates = _dateTimes.OrderBy(x => x); foreach (var dateTime in sortedDates) { if (previous != null) { total += dateTime - previous.Value; } ++quotient; previous = dateTime; } return quotient > 0 ? (TimeSpan.FromMilliseconds(total.TotalMilliseconds/quotient)) as TimeSpan? : null; } } } 
0
source

All Articles