Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace ProfilingHelper
- {
- class Program
- {
- static void Main(string[] args)
- {
- var profile = new Profile();
- using (profile["All"])
- {
- for (int i = 0; i < 10; i++)
- {
- using (profile["Part A"]) Thread.Sleep(10);
- using (profile["Part B"]) Thread.Sleep(20);
- using (profile["Part C"]) Thread.Sleep(5);
- }
- }
- Console.WriteLine(profile.StringResult());
- Console.ReadLine();
- }
- }
- public class Profile
- {
- Dictionary<string, Profiler> profilers = new Dictionary<string, Profiler>();
- public Profiler this[string index]
- {
- get
- {
- if (!profilers.ContainsKey(index)) profilers[index] = new Profiler();
- return profilers[index].Start();
- }
- }
- public Dictionary<string, int> Results()
- {
- return profilers.ToDictionary(x => x.Key, x => x.Value.ElapsedMS());
- }
- public string StringResult()
- {
- var results = Results().OrderByDescending(x => x.Value);
- var sb = new StringBuilder();
- foreach (var r in results)
- sb.Append(r.Key).Append(" = ").Append(r.Value).AppendLine("ms");
- return sb.ToString();
- }
- }
- public class Profiler : IDisposable
- {
- Stopwatch sw = new Stopwatch();
- public Profiler Start() { sw.Start(); return this; }
- public void Stop() { sw.Stop(); }
- public int ElapsedMS()
- {
- return (int)sw.ElapsedMilliseconds;
- }
- public void Dispose()
- {
- Stop();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement