Stopwatch 類別

定義

提供一組方法和屬性,您可以使用這些方法和屬性,精確地測量已耗用時間。

C#
public class Stopwatch
繼承
Stopwatch

範例

下列範例示範如何使用 Stopwatch 類別來判斷應用程式的運行時間。

C#
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 類別來計算效能數據。

C#
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-10000.
                        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);
            }
        }
     }
}

備註

Stopwatch實例可以測量一個間隔的經過時間,或跨多個間隔的經過時間總計。 在典型的 Stopwatch 案例中,您會呼叫 Start 方法,最後 Stop 呼叫 方法,然後使用 屬性檢查經過的時間 Elapsed

Stopwatch實例正在執行或停止;使用 IsRunning 來判斷 的Stopwatch目前狀態。 使用 Start 開始測量經過的時間;用來 Stop 停止測量經過的時間。 透過屬性 ElapsedElapsedMillisecondsElapsedTicks查詢經過的時間值。 您可以在實例執行或停止時查詢經過的時間屬性。 執行 時 Stopwatch ,經過的時間屬性會穩定增加;當實例停止時,它們會維持不變。

根據預設,實例的 Stopwatch 經過時間值等於所有測量時間間隔的總計。 每個呼叫 Start 都會開始計算累計經過的時間;每個呼叫結束 Stop 目前的間隔度量,並凍結累計經過的時間值。 Reset使用方法來清除現有Stopwatch實例中累積經過的時間。

測量 Stopwatch 經過的時間,方法是計算基礎定時器機制中的定時器刻度。 如果已安裝的硬體和操作系統支援高解析度性能計數器,則類別會 Stopwatch 使用該計數器來測量經過的時間。 否則,類別 Stopwatch 會使用系統定時器來測量經過的時間。 Frequency使用 和 IsHighResolution 欄位來判斷計時實作的有效Stopwatch位數和解析度。

類別可協助操作Managed程式 Stopwatch 代碼內的計時相關性能計數器。 具體而言, Frequency 欄位和 GetTimestamp 方法可用來取代非受控 Windows API QueryPerformanceFrequencyQueryPerformanceCounter

備註

在多處理器計算機上,線程執行所在的處理器並不重要。 不過,由於 BIOS 或硬體抽象層中的錯誤 (HAL) ,因此您可以在不同的處理器上取得不同的計時結果。 若要指定線程的處理器親和性,請使用 ProcessThread.ProcessorAffinity 方法。

建構函式

Stopwatch()

初始化 Stopwatch 類別的新執行個體。

欄位

Frequency

取得計時器頻率,做為每秒的刻度數。 此欄位為唯讀。

IsHighResolution

指示計時器是否以高解析度效能計數器為基礎。 此欄位為唯讀。

屬性

Elapsed

取得目前執行個體所測量的已耗用時間總和。

ElapsedMilliseconds

取得目前執行個體所測量的已耗用時間總和,以毫秒為單位。

ElapsedTicks

取得目前執行個體所測量的已耗用時間總和,以計時器刻度為單位。

IsRunning

取得值,指出 Stopwatch 計時器是否執行中。

方法

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetElapsedTime(Int64)

取得經過的時間, startingTimestamp 因為使用 GetTimestamp()擷取的值。

GetElapsedTime(Int64, Int64)

取得使用 GetTimestamp()擷取兩個時間戳之間的經過時間。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetTimestamp()

取得計時器機制中的目前刻度數。

GetType()

取得目前執行個體的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
Reset()

停止時間間隔測量並將已耗用時間重設為零。

Restart()

停止時間間隔測量,並將耗用時間重設為零,然後開始測量耗用時間。

Start()

啟動或繼續測量間隔的已耗用時間。

StartNew()

初始化新的 Stopwatch 執行個體,將已耗用時間屬性設定為零,然後開始測量已耗用時間。

Stop()

停止測量間隔的已耗用時間。

ToString()

以字串的形式傳 Elapsed 回時間。

ToString()

傳回代表目前物件的字串。

(繼承來源 Object)

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另請參閱