Skip to content

Instantly share code, notes, and snippets.

@christopherbauer
Created May 17, 2016 12:57
Show Gist options
  • Select an option

  • Save christopherbauer/d76405b680f8a6da6e98b84077001c2a to your computer and use it in GitHub Desktop.

Select an option

Save christopherbauer/d76405b680f8a6da6e98b84077001c2a to your computer and use it in GitHub Desktop.
public static class StopwatchUtil
{
public class StopwatchRecord
{
public DateTime StartTime { get; set; }
public string ActionName { get; set; }
public TimeSpan Elapsed { get; set; }
public override string ToString()
{
return string.Format("{0} - {1}: {2}", StartTime.ToShortDateString(), ActionName, Elapsed.ToString(@"hh'h'mm'm'ss's.'fffffff'ms'"));
}
}
public static List<StopwatchRecord> StopwatchHistory = new List<StopwatchRecord>();
public static StopwatchRecord Time(Action action, [CallerMemberName]string name = null)
{
var stopwatchRecord = new StopwatchRecord();
if (Debugger.IsAttached)
{
var startTime = DateTime.Now;
var stopWatch = Stopwatch.StartNew();
action();
stopWatch.Stop();
stopwatchRecord = new StopwatchRecord
{
StartTime = startTime,
ActionName = name,
Elapsed = stopWatch.Elapsed
};
StopwatchHistory.Add(stopwatchRecord);
}
else
{
action();
}
return stopwatchRecord;
}
public static void TimeAndWriteToDebug(Action action, [CallerMemberName]string name = null)
{
Debug.WriteLine(Time(action, name));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment