计算一段程序的耗时是我们在编程中很常见的用法,那这节内容就通过实例的方式来演示几种常用的统计耗时的方法。
方法一:stopwatch
static void Main(string[] args)
{
Stopwatch swt = new Stopwatch();
swt.Start();
Thread.Sleep(999);
swt.Stop();
Console.WriteLine($"程序耗时为:{sw.ElapsedMilliseconds} ms");
Console.ReadKey();
}
最常用的计算耗时的就是使用Stopwatch,使用的时候需要引用命名空间:System.Diagnostics.
运行结果:程序耗时为:1012 ms
**************************************************************************************************************
方法二:DateTime.Now
static void Main(string[] args)
{
var start = DateTime.Now;
Thread.Sleep(999);
var stop = DateTime.Now;
Console.WriteLine($"程序耗时为:{(stop - start).TotalMilliseconds} ms");
Console.ReadKey();
}
运行结果:程序耗时为:1012.2267 ms
**************************************************************************************************************