Stopwatch
class Program
{
static void Main(string[] args)
{
long timestamp = Stopwatch.GetTimestamp(); //获取计时器机制中的当前刻度数
long frequency = Stopwatch.Frequency;//获取以每秒刻度数表示的计时器频率
bool isHighResolution = Stopwatch.IsHighResolution; //指示计时器是否基于高分辨率性能计数器
Stopwatch stopWatch = new Stopwatch();
//等效于:
//Stopwatch stopWatch = Stopwatch.StartNew();
//开始计时
stopWatch.Start();
Thread.Sleep(100);
// 此时stopWatch.ElapsedMilliseconds为100
stopWatch.Reset();//停止时间测量并将运行时间置零
Thread.Sleep(100);
// 此时stopWatch.ElapsedMilliseconds为0
stopWatch.Start();
Thread.Sleep(100);
stopWatch.Restart();//停止时间测量并将运行时间置零,再重新开始。相当于Reset再Start
Thread.Sleep(200);
//结束计时
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;//以TimeSpan结构总运行时间
long tsm = stopWatch.ElapsedMilliseconds;//以毫秒为单位表示总运行时间
long tst = stopWatch.ElapsedTicks;//以计时器刻度表示总运行时间
//格式化TimeSpan
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
//输出
Console.WriteLine("RunTime: " + elapsedTime);
Console.WriteLine("RunTime(Millisecond): " + tsm);
Console.WriteLine("RunTick: " + tst);
}
}
如果 Stopwatch 类使用高分辨率性能计数器,则 GetTimestamp 返回该计数器的当前值。 如果 Stopwatch 类使用系统计时器,则 GetTimestamp 返回 DateTime.Now 实例的当前 DateTime.Ticks 属性。