Example #1
0
        static void Main(string[] args)
        {
            PerformanceScope rootScope = null;

            using (rootScope = new PerformanceScope(nameof(Main)))
            {
                Console.WriteLine("Hello World!");
                for (int i = 0; i < 10; i++)
                {
                    TestMethod1();
                }

                for (int i = 0; i < 50; i++)
                {
                    TestMethod2();
                    Thread.Sleep(10);
                }
            }

            var outs = new StringWriter();

            rootScope.Report(outs);

            Debug.WriteLine(outs.ToString());
        }
 public PerformanceScope(string name)
 {
     if (stack.Count == 0)
     {
         Name      = name;
         Stopwatch = new Stopwatch();
         instance  = this;
     }
     else
     {
         var currentCounter = stack.Peek();
         if (currentCounter.Children == null)
         {
             currentCounter.Children = new List <PerformanceScope>();
         }
         instance = currentCounter.Children.FirstOrDefault(c => c.Name == name);
         if (instance == null)
         {
             Name      = name;
             Stopwatch = new Stopwatch();
             instance  = this;
             currentCounter.Children.Add(instance);
         }
     }
     stack.Push(instance);
     instance.CallCount++;
     instance.Stopwatch.Start();
 }
 private void Report(TextWriter outs, PerformanceScope node, string indent = "")
 {
     outs.WriteLine($"{indent}{node.Name}:");
     outs.WriteLine($"{indent}  CallCount: {node.CallCount}");
     outs.WriteLine($"{indent}  TotalSeconds: {node.Stopwatch.Elapsed.TotalSeconds:0.0}");
     if (node.Children != null)
     {
         if (node.Children.Count > 1)
         {
             double totalSeconds = node.Children.Aggregate(0D, (s, ps) => s + ps.Stopwatch.Elapsed.TotalSeconds);
             outs.WriteLine($"{indent}  ChildTotalSeconds: {totalSeconds:0.0}");
         }
         var childIndent = indent + "  ";
         foreach (var child in node.Children)
         {
             Report(outs, child, childIndent);
         }
     }
 }