我做了一个非常简单的方法来测量Action的执行速度,这对我来说有好处,我可以在需要时重用它,以及我必须测量的任何代码。
对我来说,一个 DateTime 就足够了,但它很容易从 DateTime 适应到Stopwatch。
public static TimeSpan MeasureTime(Action action)
{
DateTime start = DateTime.Now;
if (action == null)
{
throw new ArgumentNullException("action");
}
try
{
action();
}
catch (Exception ex)
{
Debugger.Log(1, "Measuring",ex.ToString());
}
return DateTime.Now - start;
}
如何使用它?:
private static void StressTest()
{
List<TimeSpan> tss = new List<TimeSpan>();
for (int i = 0; i < 100; i++)
{
// here is the measuring:
var ts = MeasureTime(() => instance.Method("param1"));
tss.Add(ts);
}
Console.WriteLine("Max: {0}", tss.Max());
Console.WriteLine("Min: {0}", tss.Min());
Console.WriteLine("Avg: {0}", TimeSpan.FromMilliseconds(tss.Average(i => i.TotalMilliseconds)));
}
或者:
var ts = MeasureTime(() =>
{
// Some intensive stuff here
int a = 1;
// more here
int b = 2;
// and so on
});