Advertisement
NPSF3000

Simple Profiling Helper

Aug 26th, 2013
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.99 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8.  
  9. namespace ProfilingHelper
  10. {
  11.     class Program
  12.     {
  13.         static void Main(string[] args)
  14.         {
  15.             var profile = new Profile();
  16.  
  17.             using (profile["All"])
  18.             {
  19.                 for (int i = 0; i < 10; i++)
  20.                 {
  21.                     using (profile["Part A"]) Thread.Sleep(10);
  22.  
  23.                     using (profile["Part B"]) Thread.Sleep(20);
  24.  
  25.                     using (profile["Part C"]) Thread.Sleep(5);
  26.                 }
  27.             }
  28.             Console.WriteLine(profile.StringResult());
  29.             Console.ReadLine();
  30.         }
  31.     }
  32.  
  33.     public class Profile
  34.     {
  35.         Dictionary<string, Profiler> profilers = new Dictionary<string, Profiler>();
  36.         public Profiler this[string index]
  37.         {
  38.             get
  39.             {
  40.                 if (!profilers.ContainsKey(index)) profilers[index] = new Profiler();
  41.                 return profilers[index].Start();
  42.             }
  43.         }
  44.  
  45.         public Dictionary<string, int> Results()
  46.         {
  47.             return profilers.ToDictionary(x => x.Key, x => x.Value.ElapsedMS());
  48.         }
  49.  
  50.         public string StringResult()
  51.         {
  52.             var results = Results().OrderByDescending(x => x.Value);
  53.  
  54.             var sb = new StringBuilder();
  55.  
  56.             foreach (var r in results)
  57.                 sb.Append(r.Key).Append(" = ").Append(r.Value).AppendLine("ms");
  58.             return sb.ToString();
  59.         }
  60.  
  61.     }
  62.  
  63.     public class Profiler : IDisposable
  64.     {
  65.         Stopwatch sw = new Stopwatch();
  66.         public Profiler Start() { sw.Start(); return this; }
  67.         public void Stop() { sw.Stop(); }
  68.  
  69.         public int ElapsedMS()
  70.         {
  71.             return (int)sw.ElapsedMilliseconds;
  72.         }
  73.         public void Dispose()
  74.         {
  75.             Stop();
  76.         }
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement