/* * Copyright (c) 2005-2006 Erik Tigerholm * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ using System; using System.Collections.Generic; using System.Text; namespace OpenTraffic { public class Profile { private long startTicks; private class ProfileInformation { public ProfileInformation(string key, ProfileInformation parent) { this.key = key; ticks = 0; childs = new Dictionary(); this.parent = parent; } public string Key { get { return key; } } private string key; public long ticks; private long lastStartTick; private long number; public ProfileInformation parent; public IDictionary childs; public ProfileInformation Start(string key) { if (!childs.ContainsKey(key)) { childs.Add(key, new ProfileInformation(key, this)); } childs[key].lastStartTick = DateTime.Now.Ticks; childs[key].number++; return childs[key]; } public ProfileInformation Stop() { ticks += DateTime.Now.Ticks - lastStartTick; return this.parent; } public override string ToString() { return ToString("", 0); } public string ToString(long ticks) { return ToString("",ticks); } public string ToString(String tabs, long parentTicks) { string str = tabs + key + ": #" + number + "\t" + ticks; str += "\t" + ticks / TimeSpan.TicksPerSecond+"s"; if (number != 0) { str += "\t"+(int)(ticks / number); } if (parentTicks != 0) { str += "\t" + (100 * ticks / parentTicks) + "%"; } str += "\r\n"; foreach (KeyValuePair child in childs) { str += child.Value.ToString(tabs + " ", ticks); } return str; } } private ProfileInformation activeProfileInformation; private ProfileInformation rootProfileInformation; public Profile() { rootProfileInformation = new ProfileInformation("root",null); activeProfileInformation = rootProfileInformation; startTicks = DateTime.Now.Ticks; } public void Start(string name) { activeProfileInformation = activeProfileInformation.Start(name); } public void Stop(string key) { while (!activeProfileInformation.Key.Equals(key)) { activeProfileInformation = activeProfileInformation.Stop(); } activeProfileInformation = activeProfileInformation.Stop(); } public override string ToString() { rootProfileInformation.ticks = DateTime.Now.Ticks - startTicks; return rootProfileInformation.ToString(); } } }