using System.Collections.Generic;
using System.Diagnostics;
public static class PerfTimer
Stopwatch watch = Stopwatch.StartNew ();
var diff = watch.ElapsedMilliseconds - lastTime;
lastTime = watch.ElapsedMilliseconds;
internal long Finalize ()
var total = watch.ElapsedMilliseconds;
static private List<LappedWatch> stopwatches = new List<LappedWatch> ();
static StringBuilder log = new StringBuilder ();
static private int totalStopwatches => stopwatches.Count;
static private LappedWatch lastWatch => stopwatches[totalStopwatches - 1];
static string TabLevel => new String ('\t', totalStopwatches);
[Conditional ("PERF_LOG")]
static public void StartTimer (string name)
log.Append ($"{TabLevel}{name}:\n");
stopwatches.Add (new LappedWatch ());
[Conditional ("PERF_LOG")]
static public void StopTimer ()
if (totalStopwatches == 0)
throw new ArgumentNullException ("No Timer could be found. Did you call StartTimer first?");
var isLast = totalStopwatches == 1;
var indenting = isLast ? "" : TabLevel;
log.Append ($"{indenting}Total: {lastWatch.Finalize ()}\n");
stopwatches.RemoveAt (totalStopwatches - 1);
[Conditional ("PERF_LOG")]
static public void Log (string name)
log.Append ($"{TabLevel}{name}: {lastWatch.Lap ()} \n");
[Conditional ("PERF_LOG")]
static public void ForceStop ()
while (totalStopwatches > 0)
public static void Main()
PerfTimer.StartTimer("Test");
PerfTimer.StartTimer("Test3");
PerfTimer.Log("SubTest");
PerfTimer.Log("SubTest2");