Skip to content

Instantly share code, notes, and snippets.

@costr
Last active July 8, 2021 21:02
Show Gist options
  • Save costr/b097a03e3b2e4fe54063130f0ffc1213 to your computer and use it in GitHub Desktop.
Save costr/b097a03e3b2e4fe54063130f0ffc1213 to your computer and use it in GitHub Desktop.
Execution time logging in C# with usings
using System;
using System.Diagnostics;
namespace Tools.Debugging
{
public class ExecutionTimeLogger : IDisposable
{
private readonly Stopwatch watch;
private readonly string _titleForWhatIsBeingTracked;
private readonly string _callingMethodName;
public ExecutionTimeLogger(string titleForWhatIsBeingTracked, [CallerMemberName]string callingMethodName = "")
{
#if DEBUG
_titleForWhatIsBeingTracked = titleForWhatIsBeingTracked;
_callingMethodName = callingMethodName;
watch = new Stopwatch();
watch.Start();
#endif
}
public void Dispose()
{
#if DEBUG
watch.Stop();
var log = $"{_callingMethodName}: {_titleForWhatIsBeingTracked} ran for: {watch.ElapsedMilliseconds} ms or {TimeSpan.FromMilliseconds(watch.ElapsedMilliseconds).Seconds} seconds";
Debug.WriteLine(log);
#endif
}
}
}
using Tools.Debugging;
namespace Tools.Examples
{
public class ExecutionTimeLoggerExample
{
public ExecutionTimeLoggerExample(string titleForWhatIsBeingTracked)
{
using(new ExecutionTimeLogger("Example with delay"))
System.Threading.Thread.Sleep(500);
/*
* Output should show in the Diagnostics Tools window under the Events tab as: "ExecutionTimeLoggerExample: Example with delay ran for: 500 ms or 0 seconds"
* NOTE: This will only ouput IF you're running in DEBUG mode
*/
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment