using System; using System.Diagnostics; namespace SemiColinGames { public class Timer { private readonly Stopwatch stopwatch = new Stopwatch(); private readonly double targetTime; private readonly string name; private readonly int[] histogram = new int[21]; private double startTime = 0.0; private int totalFrames = 0; public Timer(double targetTime, string name) { this.targetTime = targetTime; this.name = name; } public void Start() { startTime = stopwatch.Elapsed.TotalSeconds; stopwatch.Start(); } public void Stop() { stopwatch.Stop(); totalFrames++; double frameTime = stopwatch.Elapsed.TotalSeconds - startTime; int bucket = FMath.Clamp((int) (10.0f * frameTime / targetTime), 0, 20); histogram[bucket]++; } public void DumpStats() { Debug.WriteLine(name + ".DumpStats():"); for (int i = 0; i < histogram.Length; i++) { int value = histogram[i]; if (value == 0) { continue; } // Every star is one percent. int numStars = FMath.Clamp(100 * value / totalFrames, 1, 100); string prefix; if (i == histogram.Length - 1) { prefix = " 200+%: "; } else { prefix = String.Format("{0,3}-{1,3}%: ", i * 10, (i + 1) * 10); } string stars = new string('*', numStars); Debug.WriteLine(String.Format("{0}{1,-100} {2}", prefix, stars, value)); } } } }