Skip to content

Instantly share code, notes, and snippets.

@omerfarukz
Created April 7, 2016 11:35
Show Gist options
  • Save omerfarukz/428fb57e31d66a48cea9bf5c078ace35 to your computer and use it in GitHub Desktop.
Save omerfarukz/428fb57e31d66a48cea9bf5c078ace35 to your computer and use it in GitHub Desktop.
public class MiniProfiler : IDisposable
{
private Stopwatch _stopWatch;
private List<ProfilerEvent> _events;
public MiniProfiler()
{
_events = new List<ProfilerEvent>();
}
public void Start()
{
if (IsRunning())
{
_stopWatch.Restart();
Step("Restarted");
}
else
{
if (_stopWatch == null)
_stopWatch = new Stopwatch();
_stopWatch.Start();
Step("Started");
}
}
public void Stop()
{
if (!IsRunning())
return;
_stopWatch.Stop();
_stopWatch = null;
}
public IDisposable Step(string name)
{
return Step(name, null);
}
public IDisposable Step(string name, string data)
{
if (!IsRunning())
return NullDisposable.CreateNew();
var profilerEvent = new ProfilerEvent();
profilerEvent.Name = name;
profilerEvent.Data = data;
profilerEvent.ElapsedMilliseconds = _stopWatch.ElapsedTicks;
return new ProfilerStep(profilerEvent, (e) => StepFinishedCallback(e));
}
private void StepFinishedCallback(ProfilerEvent e)
{
if (_stopWatch != null)
e.TotalMilliseconds = _stopWatch.ElapsedMilliseconds;
_events.Add(e);
}
private bool IsRunning()
{
if (_stopWatch == null || !_stopWatch.IsRunning)
return false;
return true;
}
public void Dispose()
{
Stop();
}
public override string ToString()
{
return string.Join(Environment.NewLine, _events);
}
public class ProfilerStep : IDisposable
{
private Stopwatch _stopWatch;
private ProfilerEvent _profilerEvent;
private Action<ProfilerEvent> _disposeAction;
public long ElapsedMilliseconds { get; private set; }
public ProfilerStep(ProfilerEvent profilerEvent, Action<ProfilerEvent> disposeAction)
{
if (profilerEvent == null)
throw new ArgumentException("profilerEvent");
_profilerEvent = profilerEvent;
_disposeAction = disposeAction;
_stopWatch = new Stopwatch();
_stopWatch.Start();
}
public void Dispose()
{
_stopWatch.Stop();
_profilerEvent.ElapsedMilliseconds = _stopWatch.ElapsedMilliseconds;
if (_disposeAction != null)
{
_disposeAction(_profilerEvent);
}
_stopWatch = null;
}
}
public class ProfilerEvent
{
public long ElapsedMilliseconds { get; set; }
public long TotalMilliseconds { get; set; }
public string Name { get; set; }
public string Data { get; set; }
public override string ToString()
{
return string.Format("{0}\t{1}\t{2}\t{3}", TotalMilliseconds, ElapsedMilliseconds, Name, Data);
}
}
public class NullDisposable : IDisposable
{
public void Dispose()
{ }
public static IDisposable CreateNew()
{
return new NullDisposable();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment