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毫秒。

 

 

 

 

本文转自夜&枫博客园博客,原文链接:http://www.cnblogs.com/newstart/archive/2012/09/21/2696884.html,如需转载请自行联系原作者
相关文章
|
C# Windows Java
C#中各种计时器 Stopwatch、TimeSpan
1、使用 Stopwatch 类 (System.Diagnostics.Stopwatch)Stopwatch 实例可以测量一个时间间隔的运行时间,也可以测量多个时间间隔的总运行时间。
2238 0
|
18天前
|
开发框架 前端开发 .NET
C#编程与Web开发
【4月更文挑战第21天】本文探讨了C#在Web开发中的应用,包括使用ASP.NET框架、MVC模式、Web API和Entity Framework。C#作为.NET框架的主要语言,结合这些工具,能创建动态、高效的Web应用。实际案例涉及企业级应用、电子商务和社交媒体平台。尽管面临竞争和挑战,但C#在Web开发领域的前景将持续拓展。
|
18天前
|
SQL 开发框架 安全
C#编程与多线程处理
【4月更文挑战第21天】探索C#多线程处理,提升程序性能与响应性。了解C#中的Thread、Task类及Async/Await关键字,掌握线程同步与安全,实践并发计算、网络服务及UI优化。跟随未来发展趋势,利用C#打造高效应用。
|
18天前
|
存储 安全 网络安全
C#编程的安全性与加密技术
【4月更文挑战第21天】C#在.NET框架支持下,以其面向对象和高级特性成为安全软件开发的利器。本文探讨C#在安全加密领域的应用,包括使用System.Security.Cryptography库实现加密算法,利用SSL/TLS保障网络传输安全,进行身份验证,并强调编写安全代码的重要性。实际案例涵盖在线支付、企业应用和文件加密,展示了C#在应对安全挑战的同时,不断拓展其在该领域的潜力和未来前景。
|
18天前
|
人工智能 C# 开发者
C#编程中的图形界面设计
【4月更文挑战第21天】本文探讨了C#在GUI设计中的应用,介绍了Windows Forms、WPF和UWP等常用框架,强调了简洁界面、响应式设计和数据绑定等最佳实践。通过实际案例,展示了C#在企业应用、游戏开发和移动应用中的GUI实现。随着技术发展,C#在GUI设计的未来将趋向于跨平台、更丰富的组件和AI集成,为开发者创造更多可能性。
|
18天前
|
存储 算法 C#
C#编程与数据结构的结合
【4月更文挑战第21天】本文探讨了C#如何结合数据结构以构建高效软件,强调数据结构在C#中的重要性。C#作为面向对象的编程语言,提供内置数据结构如List、Array和Dictionary,同时也支持自定义数据结构。文章列举了C#实现数组、链表、栈、队列等基础数据结构的示例,并讨论了它们在排序、图算法和数据库访问等场景的应用。掌握C#数据结构有助于编写高性能、可维护的代码。
|
18天前
|
开发框架 Linux C#
C#编程的跨平台应用
【4月更文挑战第21天】C#与.NET Core的结合使得跨平台应用开发变得高效便捷,提供统一编程模型和高性能。丰富的类库、活跃的社区支持及Visual Studio Code、Xamarin等工具强化了其优势。广泛应用在企业系统、云服务和游戏开发中,虽面临挑战,但随着技术进步,C#在跨平台开发领域的前景广阔。
|
18天前
|
人工智能 C# 云计算
C#编程的未来发展趋向
【4月更文挑战第21天】C#编程未来将深化跨平台支持,强化云计算与容器技术集成,如.NET Core、Docker。在AI和ML领域,C#将提供更丰富框架,与AI芯片集成。语言和工具将持续创新,优化异步编程,如Task、async和await,提升多核性能。开源生态的壮大将吸引更多开发者,共创更多机遇。
|
18天前
|
程序员 C#
C#编程中的面向对象编程思想
【4月更文挑战第21天】本文探讨了C#中的面向对象编程,包括类、对象、封装、继承和多态。类是对象的抽象,定义属性和行为;对象是类的实例。封装隐藏内部细节,只暴露必要接口。继承允许类复用和扩展属性与行为,而多态使不同类的对象能通过相同接口调用方法。C#通过访问修饰符实现封装,使用虚方法和抽象方法实现多态。理解并应用这些概念,能提升代码的清晰度和可扩展性,助你成为更好的C#程序员。
|
18天前
|
开发框架 安全 .NET
C#编程高手的成长之路
【4月更文挑战第21天】本文揭示了成为C#编程高手的路径:牢固掌握基础知识和面向对象编程,深入了解C#特性如泛型和委托,精通ASP.NET等框架工具,养成良好编程习惯,持续学习实践并参与开源项目,勇于挑战创新。通过这些步骤,不断提升编程技能,迈向C#编程的巅峰。