StopWatch 与 TimeSpan 详解

Posted xiefang2008

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了StopWatch 与 TimeSpan 详解相关的知识,希望对你有一定的参考价值。

转自:http://www.cnblogs.com/newstart/archive/2012/09/21/2696884.html

最近项目使用socket通信,要测试接受时间和解析时间,达到微妙级别,这里在MSDN上找的资料记录下:

StopWatch

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 对象表示时间间隔或持续时间,按正负天数、小时数、分钟数、秒数以及秒的小数部分进行度量。用于度量持续时间的最大时间单位是天。更大的时间单位(如月和年)的天数不同,因此为保持一致性,时间间隔以天为单位来度量。

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 = " {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 following output. It " +
            "creates several TimeSpan objects and displays " +
            "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(英语: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毫秒。

  

 

 

以上是关于StopWatch 与 TimeSpan 详解的主要内容,如果未能解决你的问题,请参考以下文章

Thread.Sleep(TimeSpan) 有多准确?

C# Stopwatch获取循环中某操作的时间消耗

(转)C# Stopwatch详解

Rxjava2 Observable的数据变换详解及实例

StopWatch 监控Java代码运行时间和分析性能

Rxjava2 Observable的数据变换详解及实例