Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Threading;
- namespace ConsoleApplication2
- {
- class Program
- {
- static void Main(string[] args)
- {
- System.Diagnostics.Debug.Listeners.Add(new System.Diagnostics.ConsoleTraceListener());
- var rnd = new Random();
- while (!Console.KeyAvailable) //Simulation loop, in reality the using will usually wrap an entire method!
- {
- using (Performance.Monitor<Program>(100, 300, "This is a test loop!"))
- Thread.Sleep(rnd.Next(500));
- };
- }
- }
- public static class Performance
- {
- public static Monitor Monitor<T>(int warnMs, int errorMs, string description = null,
- [System.Runtime.CompilerServices.CallerMemberNameAttribute] string methodName = "")
- {
- return new Monitor(typeof(T), methodName, description, warnMs, errorMs);
- }
- }
- public class Monitor : IDisposable
- {
- private readonly System.Diagnostics.Stopwatch _watch;
- Type _callerType;
- private readonly string _methodName;
- string _description;
- int _warnMs, _errorMs;
- public Monitor(Type callerType, string methodName, string description, int warnMs, int errorMs)
- {
- _watch = System.Diagnostics.Stopwatch.StartNew();
- _callerType = callerType;
- _methodName = methodName;
- _description = description;
- _warnMs = warnMs;
- _errorMs = errorMs;
- }
- public void Dispose()
- {
- _watch.Stop();
- var prefix = _watch.ElapsedMilliseconds > _errorMs ? "ERROR: " :
- _watch.ElapsedMilliseconds > _warnMs ? "WARNING: " : "";
- if (!string.IsNullOrWhiteSpace(_description))
- _description = "\nDescription: " + _description;
- System.Diagnostics.Debug.WriteLine(prefix + _callerType.Name + "." + _methodName + ": " + _watch.Elapsed.TotalSeconds + " seconds." + _description);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement