Did you ever have to log time taken by some chunk of code? I hate writing log statements every where to get time difference - so I came up with this :
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Threading;
6: 7: namespace TimeLogger
8: {9: class Program
10: {11: static void Main(string[] args)
12: {13: using (TimeLogger tl = new TimeLogger("sleeper"))
14: { 15: Thread.Sleep(3000); 16: } 17: } 18: } 19: }1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Diagnostics;
6: 7: namespace TimeLogger
8: {9: public sealed class TimeLogger:IDisposable
10: {11: private Stopwatch sw;
12: private string codeDescription = string.Empty;
13: public TimeLogger()
14: {15: this.sw = Stopwatch.StartNew();
16: }17: public TimeLogger(string codeDescription)
18: {19: this.codeDescription = codeDescription;
20: this.sw = Stopwatch.StartNew();
21: } 22: 23: void IDisposable.Dispose()
24: { 25: sw.Stop();26: if(string.IsNullOrEmpty(codeDescription))
27: Console.WriteLine("Time taken by = {0} ms", sw.ElapsedMilliseconds);
28: Console.WriteLine("Time taken by {0} = {1} ms",codeDescription, sw.ElapsedMilliseconds);
29: } 30: } 31: }What do you think?
No comments:
Post a Comment