测试代码耗时的时间段(.net)

//第一种方法利用System.DateTime.Now
static void SubTest()
{
DateTime beforDT = System.DateTime.Now;

//耗时巨大的代码

DateTime afterDT = System.DateTime.Now;
TimeSpan ts = afterDT.Subtract(beforDT);
Console.WriteLine("DateTime总共花费{0}ms.", ts.TotalMilliseconds);
}
//第二种用Stopwatch类(System.Diagnostics )
public void SubTest()
{
Stopwatch sw = new Stopwatch();
sw.Start();

//耗时巨大的代码 start

SortedDictionary<int, string> sd = new SortedDictionary<int, string>();
//赋值
for (int i = 0; i < 10000; i++)
{
sd.Add(i, "aa" + i);
}
StringBuilder sbd = new StringBuilder();
foreach (var d in sd)
{
sbd.Append("键:" + d.Key + "值:" + d.Value + ";");
}
//Console.WriteLine("输出SortedDictionary:" + sbd.ToString());
//end
sw.Stop();
TimeSpan ts2 = sw.Elapsed;
Console.WriteLine("Stopwatch总共花费{0}ms.", ts2.TotalMilliseconds);
}

原文地址:https://www.cnblogs.com/gyjjyg/p/7018348.html