第一种方法利用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
static void SubTest()
{
Stopwatch sw = new Stopwatch();
sw.Start();
//耗时巨大的代码
sw.Stop();
TimeSpan ts2 = sw.Elapsed;
Console.WriteLine("Stopwatch总共花费{0}ms.", ts2.TotalMilliseconds);
}
Stopwatch sw = new Stopwatch();
//开始计时
sw.Start();
//重新设置为零
sw.Reset();
//重新设置并开始计时
sw.Restart();
//结束计时
sw.Stop();
//获取运行时间间隔
TimeSpan ts = sw.Elapsed;
//获取运行时间[毫秒]
long times = sw.ElapsedMilliseconds;
//获取运行的总时间
long times2 = sw.ElapsedTicks;
//判断计时是否正在进行[true为计时]
bool isrun = sw.IsRunning;
//获取计时频率
long frequency = Stopwatch.Frequency;