using System; using System.Collections.Generic; namespace BestHTTP.Timings { public sealed class TimingCollector { /// /// When the TimingCollector instance created. /// public DateTime Start { get; private set; } /// /// List of added events. /// public List Events { get; private set; } public TimingCollector() { this.Start = DateTime.Now; } /// /// Add an event. Duration is calculated from the previous event or start of the collector. /// public void Add(string name) { if (this.Events == null) this.Events = new List(); DateTime prevEventAt = this.Start; if (this.Events.Count > 0) prevEventAt = this.Events[this.Events.Count - 1].When; this.Events.Add(new TimingEvent(name, DateTime.Now - prevEventAt)); } /// /// Add an event with a known duration. /// public void Add(string name, TimeSpan duration) { if (this.Events == null) this.Events = new List(); this.Events.Add(new TimingEvent(name, duration)); } public TimingEvent FindFirst(string name) { if (this.Events == null) return TimingEvent.Empty; for (int i = 0; i < this.Events.Count; ++i) { if (this.Events[i].Name == name) return this.Events[i]; } return TimingEvent.Empty; } public TimingEvent FindLast(string name) { if (this.Events == null) return TimingEvent.Empty; for (int i = this.Events.Count - 1; i >= 0; --i) { if (this.Events[i].Name == name) return this.Events[i]; } return TimingEvent.Empty; } public override string ToString() { string result = string.Format("[TimingCollector Start: '{0}' ", this.Start.ToLongTimeString()); if (this.Events != null) foreach (var @event in this.Events) result += '\n' + @event.ToString(); result += "]"; return result; } } }