查看程序运行了多少时间Stopwatch类

System.Diagnostics命名空间中的一个类。

其实就相当于一个秒表。可以不止停一次。Start方法是按下秒表开始计时,Stop方法是再次按下秒表暂停计时,IsRunning属性来判断秒表是否在运行,Reset方法将秒表清零。

它的机制如下:
如果已安装的硬件或操作系统提供了高分辨率(high-resolution)的计数器,就用那个计数器;不然就系统计时器。Frequency和IsHighResolution来判断精度和是否是高分辨率。

小提示:
对于多核计算机,是哪个核处理的一般不影响

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;

namespace _090914_ApplicationRunSpan1
{
    
class Program
    {
        
static void Main(string[] args)
        {
            Stopwatch watcher 
= new Stopwatch();
            watcher.Start();
            Thread.Sleep(
2500);
            
if (watcher.IsRunning)
                Console.WriteLine(
"The watcher is running.");
            watcher.Stop();
            Console.WriteLine(watcher.ElapsedMilliseconds.ToString()
+" Milliseconds");
            TimeSpan ts 
= watcher.Elapsed;
            Console.WriteLine(String.Format(
"{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds 
/ 10));
            Console.Read();
        }
    }
}


上面的那个程序在中间没有添加watcher.IsRunning的时候也出现过Sleep了2500ms,但显示只Sleep了2499的情况,看来也是会有随机性的。

原文地址:https://www.cnblogs.com/galaxyyao/p/1566315.html