C# Stopwatch與TimeSpan詳解


最近項目使用socket通信,要測試接受時間和解析時間,達到微妙級別,這里在MSDN上找的資料記錄下:

Stopwatch 實例可以測量一個時間間隔的運行時間,也可以測量多個時間間隔的總運行時間。 在典型的 Stopwatch 方案中,先調用 Start 方法,然后調用 Stop 方法,最后使用 Elapsed 屬性檢查運行時間。

Stopwatch 實例或者在運行,或者已停止;使用 IsRunning 可以確定 Stopwatch 的當前狀態。 使用 Start 可以開始測量運行時間;使用 Stop 可以停止測量運行時間。 通過屬性 Elapsed、ElapsedMilliseconds 或 ElapsedTicks 查詢運行時間值。 當實例正在運行或已停止時,可以查詢運行時間屬性。 運行時間屬性在 Stopwatch 運行期間穩固遞增;在該實例停止時保持不變。

默認情況下,Stopwatch 實例的運行時間值相當於所有測量的時間間隔的總和。 每次調用 Start 時開始累計運行時間計數;每次調用 Stop 時結束當前時間間隔測量,並凍結累計運行時間值。 使用 Reset 方法可以清除現有 Stopwatch 實例中的累計運行時間。

Stopwatch 在基礎計時器機制中對計時器的計時周期進行計數,從而測量運行時間。 如果安裝的硬件和操作系統支持高分辨率性能計數器,則 Stopwatch 類將使用該計數器來測量運行時間; 否則,Stopwatch 類將使用系統計數器來測量運行時間。 使用 Frequency 和 IsHighResolution 字段可以確定實現 Stopwatch 計時的精度和分辨率。

Stopwatch 類為托管代碼內與計時有關的性能計數器的操作提供幫助。 具體說來,Frequency 字段和 GetTimestamp 方法可以用於替換非托管 Win32 API QueryPerformanceFrequency 和 QueryPerformanceCounter。

 說明 
在多處理器計算機上,線程在哪個處理器上運行無關緊要。 但是,由於 BIOS 或硬件抽象層 (HAL) 中的 bug,在不同的處理器上可能會得出不同的計時結果。 若要為線程指定處理器關聯,請使用 ProcessThread.ProcessorAffinity 方法。

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);
    }
}
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);
            }
        }
     }
}

TimeSpan 對象表示時間間隔或持續時間,按正負天數、小時數、分鍾數、秒數以及秒的小數部分進行度量。用於度量持續時間的最大時間單位是天。更大的時間單位(如月和年)的天數不同,因此為保持一致性,時間間隔以天為單位來度量。

TimeSpan 對象的值是等於所表示時間間隔的刻度數。一個刻度等於 100 納秒,TimeSpan 對象的值的范圍在 MinValue 和 MaxValue 之間。

TimeSpan 值可以表示為 [-]d.hh:mm:ss.ff,其中減號是可選的,它指示負時間間隔,d 分量表示天,hh 表示小時(24 小時制),mm 表示分鍾,ss 表示秒,而 ff 為秒的小數部分。即,時間間隔包括整的正負天數、天數和剩余的不足一天的時長,或者只包含不足一天的時長。例如,初始化為 1.0e+13 刻度的 TimeSpan 對象的文本表示“11.13:46:40”,即 11 天,13 小時,46 分鍾和 40 秒。

TimeSpan 類型實現了 System.IComparable 和 System.IComparable 接口。

// Example of the TimeSpan class properties.
using System;

class TimeSpanPropertiesDemo
{
    const string headerFmt = "\n{0,-45}";
    const string dataFmt = "{0,-12}{1,8}       {2,-18}{3,21}" ;

    // Display the properties of the TimeSpan parameter.
    static void ShowTimeSpanProperties( TimeSpan interval )
    {
        Console.WriteLine( "{0,21}", interval );
        Console.WriteLine( dataFmt, "Days", interval.Days, 
            "TotalDays", interval.TotalDays );
        Console.WriteLine( dataFmt, "Hours", interval.Hours, 
            "TotalHours", interval.TotalHours );
        Console.WriteLine( dataFmt, "Minutes", interval.Minutes, 
            "TotalMinutes", interval.TotalMinutes );
        Console.WriteLine( dataFmt, "Seconds", interval.Seconds, 
            "TotalSeconds", interval.TotalSeconds );
        Console.WriteLine( dataFmt, "Milliseconds", 
            interval.Milliseconds, "TotalMilliseconds", 
            interval.TotalMilliseconds );
        Console.WriteLine( dataFmt, null, null, 
            "Ticks", interval.Ticks );
    } 

    static void Main( )
    {
        Console.WriteLine(
            "This example of the TimeSpan class properties " +
            "generates the \nfollowing output. It " +
            "creates several TimeSpan objects and \ndisplays " +
            "the values of the TimeSpan properties for each." );

        // Create and display a TimeSpan value of 1 tick.
        Console.Write( headerFmt, "TimeSpan( 1 )" );
        ShowTimeSpanProperties( new TimeSpan( 1 ) );

        // Create a TimeSpan value with a large number of ticks.
        Console.Write( headerFmt, "TimeSpan( 111222333444555 )" );
        ShowTimeSpanProperties( new TimeSpan( 111222333444555 ) );

        // This TimeSpan has all fields specified.
        Console.Write( headerFmt, "TimeSpan( 10, 20, 30, 40, 50 )" );
        ShowTimeSpanProperties( new TimeSpan( 10, 20, 30, 40, 50 ) );

        // This TimeSpan has all fields overflowing.
        Console.Write( headerFmt, 
            "TimeSpan( 1111, 2222, 3333, 4444, 5555 )" );
        ShowTimeSpanProperties(
            new TimeSpan( 1111, 2222, 3333, 4444, 5555 ) );

        // This TimeSpan is based on a number of days.
        Console.Write( headerFmt, "FromDays( 20.84745602 )" );
        ShowTimeSpanProperties( TimeSpan.FromDays( 20.84745602 ) );
    } 
} 

 結果如下

/*
This example of the TimeSpan class properties generates the
following output. It creates several TimeSpan objects and
displays the values of the TimeSpan properties for each.

TimeSpan( 1 )                                     00:00:00.0000001
Days               0       TotalDays          1.15740740740741E-12
Hours              0       TotalHours         2.77777777777778E-11
Minutes            0       TotalMinutes       1.66666666666667E-09
Seconds            0       TotalSeconds                      1E-07
Milliseconds       0       TotalMilliseconds                0.0001
                           Ticks                                 1

TimeSpan( 111222333444555 )                   128.17:30:33.3444555
Days             128       TotalDays              128.729552597865
Hours             17       TotalHours             3089.50926234875
Minutes           30       TotalMinutes           185370.555740925
Seconds           33       TotalSeconds           11122233.3444555
Milliseconds     344       TotalMilliseconds      11122233344.4555
                           Ticks                   111222333444555

TimeSpan( 10, 20, 30, 40, 50 )                 10.20:30:40.0500000
Days              10       TotalDays              10.8546302083333
Hours             20       TotalHours                   260.511125
Minutes           30       TotalMinutes                 15630.6675
Seconds           40       TotalSeconds                  937840.05
Milliseconds      50       TotalMilliseconds             937840050
                           Ticks                     9378400500000

TimeSpan( 1111, 2222, 3333, 4444, 5555 )     1205.22:47:09.5550000
Days            1205       TotalDays              1205.94941614583
Hours             22       TotalHours                28942.7859875
Minutes           47       TotalMinutes              1736567.15925
Seconds            9       TotalSeconds              104194029.555
Milliseconds     555       TotalMilliseconds          104194029555
                           Ticks                  1041940295550000

FromDays( 20.84745602 )                        20.20:20:20.2000000
Days              20       TotalDays              20.8474560185185
Hours             20       TotalHours             500.338944444444
Minutes           20       TotalMinutes           30020.3366666667
Seconds           20       TotalSeconds                  1801220.2
Milliseconds     200       TotalMilliseconds            1801220200
                           Ticks                    18012202000000
*/ 

 ps:

皮秒,符號ps(英語:picosecond ).
1皮秒等於一萬億分之一秒(10-12秒)

1,000 皮秒 = 1納秒

1,000,000 皮秒 = 1微秒

1,000,000,000 皮秒 = 1毫秒

1,000,000,000,000 皮秒 = 1秒


納秒
納秒,符號ns(英語:nanosecond ).
1納秒等於十億分之一秒(10-9秒)

1 納秒 = 1000皮秒

1,000 納秒 = 1微秒

1,000,000 納秒 = 1毫秒

1,000,000,000 納秒 = 1秒

微秒,符號μs(英語:microsecond ).
1微秒等於一百萬分之一秒(10-6秒)

0.000 001 微秒 = 1皮秒

0.001 微秒 = 1納秒

1,000 微秒 = 1毫秒

1,000,000 微秒 = 1秒

 

毫秒
毫秒,符號ms(英語:millisecond ).
1毫秒等於一千分之一秒(10-3秒)

0.000 000 001 毫秒 = 1皮秒

0.000 001 毫秒 = 1納秒

0.001 毫秒 = 1微秒

1000 毫秒 = 1秒

最好我測試出來結果是

timespan  s=00:00:00.0008025

轉換成Milliseconds  ms=0.8025毫秒。

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM