Stopwatch 类

提供一组方法和属性,可用于准确地测量运行时间。

命名空间:                   System.Diagnostics
程序集:         System(位于 System.dll)

继承层次结构

System.Object
System.Diagnostics.Stopwatch

语法:

public class Stopwatch


构造函数


名称说明
System_CAPS_pubmethodStopwatch()

初始化 Stopwatch 类的新实例。

属性


名称说明
System_CAPS_pubpropertyElapsed

获取当前实例测量得出的总运行时间。

System_CAPS_pubpropertyElapsedMilliseconds

获取当前实例测量得出的总运行时间(以毫秒为单位)。

System_CAPS_pubpropertyElapsedTicks

获取当前实例测量得出的总运行时间(用计时器刻度表示)。

System_CAPS_pubpropertyIsRunning

获取一个值,该值表示 Stopwatch 计时器是否正在运行。

方法


名称说明
System_CAPS_pubmethodEquals(Object)

确定指定的对象是否等于当前对象。(继承自 Object。)

System_CAPS_protmethodFinalize()

在垃圾回收将某一对象回收前允许该对象尝试释放资源并执行其他清理操作。(继承自 Object。)

System_CAPS_pubmethodGetHashCode()

作为默认哈希函数。(继承自 Object。)

System_CAPS_pubmethodSystem_CAPS_staticGetTimestamp()

获取计时器机制中的当前刻度数。

System_CAPS_pubmethodGetType()

获取当前实例的 Type(继承自 Object。)

System_CAPS_protmethodMemberwiseClone()

创建当前 Object 的浅表副本。(继承自 Object。)

System_CAPS_pubmethodReset()

停止时间间隔测量,并将运行时间重置为零。

System_CAPS_pubmethodRestart()

停止时间间隔测量,将运行时间重置为零,然后开始测量运行时间。

System_CAPS_pubmethodStart()

开始或继续测量某个时间间隔的运行时间。

System_CAPS_pubmethodSystem_CAPS_staticStartNew()

初始化新的 Stopwatch 实例,将运行时间属性设置为零,然后开始测量运行时间。

System_CAPS_pubmethodStop()

停止测量某个时间间隔的运行时间。

System_CAPS_pubmethodToString()

返回表示当前对象的字符串。(继承自 Object。)

字段


名称说明
System_CAPS_pubfieldSystem_CAPS_staticFrequency

获取以每秒刻度数表示的计时器频率。 此字段为只读。

System_CAPS_pubfieldSystem_CAPS_staticIsHighResolution

指示计时器是否基于高分辨率性能计数器。 此字段为只读。


备注

System_CAPS_note说明

若要查看此类型的.NET Framework 源代码,请参阅 Reference Source 您可以浏览源代码、 下载脱机查看参考资料和调试; 在逐句通过源 (包括修补程序和更新)see instructions.

一个 Stopwatch 实例可以测量运行时间为一个时间间隔或所用的时间合计多个间隔。 在典型 Stopwatch 方案中,调用 Start 方法,然后最终调用 Stop 方法,然后检查经过的时间使用 Elapsed 属性。

一个 Stopwatch 实例正在运行或已停止; 使用 IsRunning 来确定的当前状态 Stopwatch 使用 Start 开始测量运行时间; 使用 Stop 停止测量运行时间。 查询运行时间值通过属性 Elapsed, ,ElapsedMilliseconds, ,或 ElapsedTicks 正在运行或已停止实例时,您可以查询运行时间属性。 属性则稳步增多的已用时间而 Stopwatch 是运行; 它们保持不变时停止该实例。

默认情况下,运行时间值的 Stopwatch 实例等于所有规定的时间间隔的合计。 每次调用 Start 开始计数累计的运行时间; 每次调用 Stop 结束当前的时间间隔测量,并会冻结的累计运行时间值。 使用 Reset 方法清除中现有的累计已用时间 Stopwatch 实例。

 Stopwatch 通过计算基础计时器机制中的计时器刻度来测量运行时间。 如果已安装的硬件和操作系统支持高分辨率性能计数器,则 Stopwatch 类使用该计数器来测量运行时间。 否则为 Stopwatch 类使用系统计时器来测量运行时间。 使用 FrequencyIsHighResolution 字段来确定的精度和解决方法 Stopwatch 计时实现。

 Stopwatch 类托管代码中与计时相关的性能计数器的操作提供帮助。 具体而言, Frequency 字段和 GetTimestamp 方法可用来代替非托管的 Win32 Api QueryPerformanceFrequencyQueryPerformanceCounter

System_CAPS_note说明

在多处理器计算机上,它并不重要哪个处理器运行的线程。 但是,由于在 BIOS 或硬件抽象层 (HAL) 中的 bug,您可能会在不同的处理器得到不同的计时结果。 若要指定一个线程的处理器关联,请使用 ProcessThread.ProcessorAffinity 方法。

下面的示例演示如何使用 Stopwatch 类,以确定应用程序的执行时间。

using System;using System.Diagnostics;using System.Threading;class Program
{    static void Main(string[] args)
    {
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
        Thread.Sleep(10000);
        stopWatch.Stop();        
        // Get the elapsed time as a TimeSpan value.
        TimeSpan ts = stopWatch.Elapsed;        
        // Format and display the TimeSpan value.
        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);
    }
}

下面的示例演示如何使用 Stopwatch 类来计算的性能数据。

using System;using System.Diagnostics;namespace StopWatchSample
{    class OperationsTimer
    {        public static void Main()
        {
            DisplayTimerProperties();

            Console.WriteLine();
            Console.WriteLine("Press the Enter key to begin:");
            Console.ReadLine();
            Console.WriteLine();

            TimeOperations();
        }        public static void DisplayTimerProperties()
        {            // Display the timer frequency and resolution.
            if (Stopwatch.IsHighResolution)
            {
                Console.WriteLine("Operations timed using the system's 
                high-resolution performance counter.");
            }            
            else 
            {
                Console.WriteLine("Operations timed using the DateTime class.");
            }            
            long frequency = Stopwatch.Frequency;
            Console.WriteLine("  Timer frequency in ticks per second = {0}",
                frequency);            
                long nanosecPerTick = (1000L*1000L*1000L) / frequency;
                Console.WriteLine("  Timer is accurate within {0} nanoseconds", 
                nanosecPerTick);
        }        
        private static void TimeOperations()
        {            
        long nanosecPerTick = (1000L*1000L*1000L) / Stopwatch.Frequency;            
        const long numIterations = 10000;    // Define the operation title names.
                    String [] operationNames = {"Operation: Int32.Parse(\"0\")",                                        
             "Operation: Int32.TryParse(\"0\")",                   
                                    "Operation: Int32.Parse(\"a\")",                                           
                                    "Operation: Int32.TryParse(\"a\")"};
                                                
                                                
                                    // Time four different implementations for parsing
                                                          // an integer from a string. 

            for (int operation = 0; operation <= 3; operation++)
            {                // Define variables for operation statistics.
                long numTicks = 0;
                long numRollovers = 0;
                long maxTicks = 0;                
                long minTicks = Int64.MaxValue;                
                int indexFastest = -1;                
                int indexSlowest = -1;                
                long milliSec = 0;
                Stopwatch time10kOperations = Stopwatch.StartNew();                
                // Run the current operation 10001 times.
                // The first execution time will be tossed
                // out, since it can skew the average time.

                for (int i=0; i<=numIterations; i++) 
                {                    
                long ticksThisTime = 0;                    
                int inputNum;
                    Stopwatch timePerParse;                    
                    switch (operation)
                    {                        
                    case 0:                           
                     // Parse a valid integer using
                     // a try-catch statement.
                     // Start a new stopwatch timer.
                            timePerParse = Stopwatch.StartNew();                            
                            try 
                            {
                                inputNum = Int32.Parse("0");
                            }                            
                            catch (FormatException)
                            {
                                inputNum = 0;
                            }                            
                            // Stop the timer, and save the
                            // elapsed ticks for the operation.

                            timePerParse.Stop();
                            ticksThisTime = timePerParse.ElapsedTicks;                            
                            break;                       
                             case 1:                            
                            // Parse a valid integer using
                            // the TryParse statement.

                            // Start a new stopwatch timer.
                            timePerParse = Stopwatch.StartNew();                            
                            if (!Int32.TryParse("0", out inputNum))
                            { 
                                inputNum = 0;
                            }                            
                            // Stop the timer, and save the
                            // elapsed ticks for the operation.
                            timePerParse.Stop();
                            ticksThisTime = timePerParse.ElapsedTicks;                            
                            break;                       
                             case 2:                            
                             // Parse an invalid value using
                            // a try-catch statement.

                            // Start a new stopwatch timer.
                            timePerParse = Stopwatch.StartNew();                            
                            try 
                            {
                                inputNum = Int32.Parse("a");
                            }                            catch (FormatException)
                            {
                                inputNum = 0;
                            }                            
                            // Stop the timer, and save the
                            // elapsed ticks for the operation.
                            timePerParse.Stop();
                            ticksThisTime = timePerParse.ElapsedTicks;                           
                             break;                        
                            case 3:                           
                             // Parse an invalid value using
                            // the TryParse statement.

                            // Start a new stopwatch timer.
                            timePerParse = Stopwatch.StartNew();                            
                            if (!Int32.TryParse("a", out inputNum))
                            { 
                                inputNum = 0;
                            }                           
                             // Stop the timer, and save the
                            // elapsed ticks for the operation.
                            timePerParse.Stop();
                            ticksThisTime = timePerParse.ElapsedTicks;                            
                            break;                        default:                            
                            break;
                    }                    
                    // Skip over the time for the first operation,
                    // just in case it caused a one-time
                    // performance hit.
                    if (i == 0)
                    {
                        time10kOperations.Reset();
                        time10kOperations.Start();
                    }                    
                    else 
                    {                        
                    // Update operation statistics
                        // for iterations 1-10001.
                        if (maxTicks < ticksThisTime)
                        {
                            indexSlowest = i;
                            maxTicks = ticksThisTime;
                        }                        
                        if (minTicks > ticksThisTime)
                        {
                            indexFastest = i;
                            minTicks = ticksThisTime;
                        }
                        numTicks += ticksThisTime;                        
                        if (numTicks < ticksThisTime)
                        {                            
                        // Keep track of rollovers.
                            numRollovers ++;
                        }
                    }
                }  

                // Display the statistics for 10000 iterations.

                time10kOperations.Stop();
                milliSec = time10kOperations.ElapsedMilliseconds;

                Console.WriteLine();
                Console.WriteLine("{0} Summary:", operationNames[operation]);
                Console.WriteLine("  Slowest time:  #{0}/{1} = {2} ticks",
                    indexSlowest, numIterations, maxTicks);
                Console.WriteLine("  Fastest time:  #{0}/{1} = {2} ticks",
                    indexFastest, numIterations, minTicks);
                Console.WriteLine("  Average time:  {0} ticks = {1} nanoseconds", 
                    numTicks / numIterations, 
                    (numTicks * nanosecPerTick) / numIterations );
                Console.WriteLine("Total time looping through {0} operations: 
                {1} milliseconds", 
                    numIterations, milliSec);
            }
        }
     }
}

备注:摘自https://msdn.microsoft.com/zh-cn/library/system.diagnostics.stopwatch(v=vs.110).aspx