StopWatch使用的命名空间:
using System.Diagnostics;
StopWatch的使用方法:
创建Stopwatch对象:stopwatch;
stopwatch计时表开启:stopwatch.Start();
stopwatch计时表关闭:stopwatch.Stop();
计算stopwatch.Stop()计时表从开启到关闭的总运行时间:
stopwatch.ElapsedTicks:返回长整型,用计时器刻度表示(微秒级别);
stopwatch.ElapsedMilliseconds:返回长整型,以毫秒为单位;
stopwatch.Elapsed:返回TimeSpan类型
计算StopWatch开启和关闭期间不执行程序时的耗时:
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
stopwatch.Stop();
Console.WriteLine("Stopwatch.ElapsedTicks:" + stopwatch.ElapsedTicks);
Console.ReadKey();
}
输出:14ns(20ns以内)
计算StopWatch开启和关闭期间执行循环程序时的耗时:
计时器从开启到关闭的总运行时间与循环中第一次DateTime.Now到循环中最后一次DateTime.Now的时间间隔进行比较:
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 1000; i++)
{
var now = DateTime.Now;
Console.WriteLine(string.Format("Ticks:{0}\tMilliseconds:{1}", now.Ticks, now.Millisecond));
}
stopwatch.Stop();
Console.WriteLine("Stopwatch.ElapsedTicks:" + stopwatch.ElapsedTicks);
Console.ReadKey();
}
574-252=322。
测试得出:使用DateTime计算程序运行的时间间隔,误差1ms内,可控。