对一段代码计时同查通常有三种方法。最简单就是用DateTime.Now来进行比较了,不过其精度只有3.3毫秒,可以通过DllImport导入QueryPerformanceFrequency和QueryPerformanceCounter,实现高精度的计时,请参考《.net平台下获取高精度时间类》。
在.NET 2.0中,新增了Stopwatch类处理计时需求,Stopwatch会优先使用高精度计时,仅当系统不支持时才会用DateTime来计时,可通过Stopwatch静态属性IsHighResolution来判断是否是高精度计时。

Stopwatch最简单的使用示例:

  1. // 开始计时
  2. Stopwatch watch = new Stopwatch();
  3. watch.Start();
  4. // 你的耗时代码
  5. // 停止计时
  6. watch.Stop();
  7. //得到运行所花费的时间
  8. Console.WriteLine(watch.Elapsed);

MSDN上的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);
            }
        }
    }
}

msdn:《Stopwatch Class

原文:http://www.it118.org/Specials/321869dd-98cb-431b-b6d2-82d973cd739d/3a6ef558-4596-459e-9918-93da13b3bb9b.htm

[转]使用Stopwatch类实现高精度计时的更多相关文章

  1. 使用StopWatch类来计时 (perf4j-0.9.16.jar 包里的类)

    public class StopWatch { static public int AN_HOUR = 60 * 60 * 1000; static public int A_MINUTE = 60 ...

  2. C# Stopwatch类_性能_时间计时器

    在研究性能的时候,完全可以使用Stopwatch计时器计算一项技术的效率.但是有时想知道某想技术的性能的时候,又常常想不起可以运用Stopwatch这个东西,太可悲了. 属性: Elapsed 获取当 ...

  3. Stopwatch 类【转】

    一般我们想要测试使用那种方法或着那种类型效率更高,使用Stopwatch类进行测试就可以,我也是现在才知道,汗一个. 先来看个小示例,如下. 前提,先引用using System.Diagnostic ...

  4. Stopwatch类学习

    1.概述:给一条大MSDN的链接关于Stopwatch类最详细的教程 ,然后看着教程自己手动敲一边,加深映象,好记性不如烂键盘,哈哈,开个玩笑! 2.类位置:这个类在哪里,这个是重点,虽然C#IDE很 ...

  5. C# Stopwatch 类

    命名空间:System.Diagnostics Stopwatch 实例可以测量一个时间间隔的运行时间,也可以测量多个时间间隔的总运行时间.在典型的 Stopwatch 方案中,先调用 Start 方 ...

  6. Stopwatch 类用于计算程序运行时间

    Stopwatch 类 命名空间:System.Diagnostics.Stopwatch 实例化:Stopwatch getTime=new Stopwatch(); 开始计时:getTime.St ...

  7. C#基础_利用Stopwatch计时器可暂停计时,继续计时

    最近程序上用到了计时功能,对某个模块进行计时,暂停的时候模块也需要暂停,启动的时候计时继续 用到了Stopwatch Stopwatch的命名空间是using System.Diagnostics; ...

  8. 用Stopwatch类获得程序运行时间

    我们可以用Stopwatch类获得程序的运行时间,在优化代码时,可以用此方法来查看优化前后程序所耗费的时间 //Stopwatch类別在System.Diagnostics命名空间里 Stopwatc ...

  9. 利用StopWatch类监控Java代码执行时间并分析性能

    springframework中的StopWatch类可以测量一个时间间隔的运行时间,也可以测量多个时间间隔的总运行时间.一般用来测量代码执行所用的时间或者计算性能数据,在优化代码性能上可以使用Sto ...

随机推荐

  1. grep 命令详解

    [root@www ~]# grep [-acinv] [--color=auto] '搜寻字符串' filename 选项与参数: -a :将 binary 文件以 text 文件的方式搜寻数据 - ...

  2. eclipse配置项目

    project facets -> dynamic web module 2.5 java -> 1.6 deployment assembly -> webapp Web Proj ...

  3. Hessian怎样实现远程调用

    1.Spring中除了提供HTTP调用器方式的远程调用,还对第三方的远程调用实现提供了支持,其中提供了对Hessian的支持. Hessian是由Caocho公司发布的一个轻量级的二进制协议远程调用实 ...

  4. python脚本生成exe可执行文件

    1.先安装第三方插件: py2exe. Get py2exe from http://www.py2exe.org/ 在download里下载与自己python对应的版本 2.写一个测试python文 ...

  5. VSS转SVN

    我们都知道VSS和SVN都是源代码的版本控制软件:最近公司准备把多年使用的VSS代码全部转到SVN中进行管理,查询了一些资料,整理一下,分享给大家 基本分三大步进行,如下: 1.去掉VSS所有绑定 2 ...

  6. linux--------------今天又遇到一个奇葩的问题,就是linux文件的权限已经是777了但是还是没有写入权限,按照下面的命令就解决了

    查看SELinux状态: 1./usr/sbin/sestatus -v      ##如果SELinux status参数为enabled即为开启状态 SELinux status:         ...

  7. SQLServer中系统存储过程sp_spaceused

    sp_spaceused 执行sp_spaceused存储过程的时候可以不用带参数,直接执行,或者exec sp_spaceused都可以,返回两个结果集: 列名 数据类型 描述 database_n ...

  8. 20.谈谈对mvc的认识。

    MVC是 模型(Model) .视图(View).控制器(Control) 的英文首字母的缩写,核心思想是:视图和用户交互 通过事件导致控制器改变 控制器改变导致模型改变 或者控制器同时改变两者 模型 ...

  9. 什么情况下会用到try-catch

    本文不区分语言,只为记录一次有收获的面试. 面试官:什么情况下用到try-catch?程序员:代码执行预料不到的情况,我会使用try-catch.面试官:什么是预料不到的情况呢?程序员:比如我要计算a ...

  10. 怎样给Myeclipse配置tomcat服务器

    http://jingyan.baidu.com/article/4853e1e53465271909f72690.html Meclipse是java Web企业级开发中最流行的工具,java we ...