È possibile utilizzare questo piccolo classe:
public class PolyStopwatch
{
readonly Dictionary<string, long> counters;
readonly Stopwatch stopwatch;
string currentLabel;
public PolyStopwatch()
{
stopwatch = new Stopwatch();
counters = new Dictionary<string, long>();
}
public void Start(string label)
{
if (currentLabel != null) Stop();
currentLabel = label;
if (!counters.ContainsKey(label))
counters.Add(label, 0);
stopwatch.Restart();
}
public void Stop()
{
if (currentLabel == null)
throw new InvalidOperationException("No counter started");
stopwatch.Stop();
counters[currentLabel] += stopwatch.ElapsedMilliseconds;
currentLabel = null;
}
public void Print()
{
if (currentLabel != null) Stop();
long totalTime = counters.Values.Sum();
foreach (KeyValuePair<string, long> kvp in counters)
Debug.Print("{0,-40}: {1,8:N0} ms ({2:P})", kvp.Key, kvp.Value, (double) kvp.Value/totalTime);
Debug.WriteLine(new string('-', 62));
Debug.Print("{0,-40}: {1,8:N0} ms", "Total time", totalTime);
}
}
usare in questo modo:
var ps = new PolyStopwatch();
ps.Start("Method1");
Method1();
ps.Stop();
// other code...
ps.Start("Method2");
Method2();
ps.Stop();
ps.Print();
Se le chiamate si susseguono, è possibile omettere Stop()
ps.Start("Method1");
Method1();
ps.Start("Method2");
Method2();
ps.Print();
Funziona bene con un ciclo:
for(int i = 0; i < 10000; i++)
{
ps.Start("Method1");
Method1();
ps.Start("Method2");
Method2();
}
ps.Print();
grazie mille !!! – user1386966
C'è qualche differenza tra scrivere sw.Restart e sw.Avviare in questo caso? – user1386966
Utilizzare Riavvia per interrompere la misurazione dell'intervallo corrente e avviare una nuova misurazione dell'intervallo (MSDN). Il riavvio cancella il tempo trascorso. – oakio