Created
May 6, 2010 09:54
-
-
Save meklarian/391975 to your computer and use it in GitHub Desktop.
quick and dirty auto-disposing timer that can be used to measure times for blocks of code by gaming the using() statement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This is not as accurate as putting a Stopwatch in your source code, but for quick and dirty profiling, good enough. I feel it is handy to be able to /abuse/use/ using() semantics for this scenario. I think this could also be improved by adding another constructor that takes a delegate to handle printing out the timer element; or perhaps a delegate to a given logging method of choice. | |
Syntax is straightforward. | |
using(new AutoTimer()) | |
{ | |
// do stuff here | |
} | |
using(new AutoTimer("working in fn()")) | |
{ | |
// stuff that allegedly is inside of fn() | |
} | |
One drawback is that the using() semantics become overhead even if you #ifdef away code for non-debug builds. I might be wrong about that, though. I'm sure someone with more knowledge than me can figure out a way for the using() block to be optimized away for a retail build. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Diagnostics; | |
namespace YourFavoriteNamespace | |
{ | |
public class AutoTimer : IDisposable | |
{ | |
public AutoTimer() | |
{ | |
_Init(); | |
} | |
public AutoTimer(string logMessage) | |
{ | |
msg = logMessage; | |
_Init(); | |
} | |
Stopwatch myTimer; | |
string msg; | |
void _Init() | |
{ | |
Trace.WriteLine(string.Format("Starting: {0}", msg)); | |
myTimer = new Stopwatch(); | |
myTimer.Start(); | |
} | |
void _Terminate() | |
{ | |
myTimer.Stop(); | |
Trace.Write(string.Format("Stopping: {0} ", msg)); | |
Trace.WriteLine(string.Format("{0}ms {1}ticks", myTimer.ElapsedMilliseconds, myTimer.ElapsedTicks)); | |
myTimer = null; | |
} | |
#region IDisposable Members | |
public void Dispose() | |
{ | |
if (!object.ReferenceEquals(myTimer, null)) | |
{ | |
_Terminate(); | |
} | |
} | |
#endregion | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment