对一段代码计时同查通常有三种方法。最简单就是用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. 毕业设计 之 二 PHP学习笔记(一)

    毕业设计 之 二 PHP学习笔记(一) 作者:20135216 平台:windows10 软件:XAMPP,DreamWeaver 一.环境搭建 1.XAMPP下载安装 XAMPP是PHP.MySQL ...

  2. mongoperf

    官方文档 mongoperf is a utility to check disk I/O performance independently of MongoDB. It times tests o ...

  3. 怎样使java程序减少内存占用(转载)

    本文收集网上关于减少java程序占用的一些小知识点 (1)别用new Boolean(). 在很多场景中Boolean类型是必须的,比如JDBC中boolean类型的set与get都是通过Boolea ...

  4. 学霸数据处理项目之数据处理网页以及后台以及C#代码部分开发者手册

    写在前面,本文将详细介绍学霸数据处理项目中的数据处理网页与后台函数,以及c#代码中每一个方法的意义及其一些在运行方面需要注意的细节,供开发人员使用,开发人员在阅读相关方法说明时请参照相关代码,对于本文 ...

  5. LeetCode Find All Anagrams in a String

    原题链接在这里:https://leetcode.com/problems/find-all-anagrams-in-a-string/ 题目: Given a string s and a non- ...

  6. lua 面向对象编程类机制实现

    lua no class It is a prototype based language. 在此语言中没有class关键字来创建类. 现代ES6, 已经添加class类. prototype bas ...

  7. Redis集群~StackExchange.redis连接Twemproxy代理服务器

    回到目录 本文是Redis集群系列的一篇文章,主要介绍使用StackExchange.Redis进行Twemproxy(文中简称TW)代理服务的连接过程,事务上,对于TW来说,我们需要理解一下它的物理 ...

  8. Leetcode: LFU Cache && Summary of various Sets: HashSet, TreeSet, LinkedHashSet

    Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the f ...

  9. JS调用OC方法并传值,OC调用JS方法并传值////////////////////////zz

     iOS开发-基于原生JS与OC方法互相调用并传值(附HTML代码)     最近项目里面有有个商品活动界面,要与web端传值,将用户在网页点击的商品id 传给客户端,也就是js交互,其实再说明白一点 ...

  10. Android开发新手学习总结(六)——android开发目录结构【图文版】

    转载链接:http://bbs.itcast.cn/thread-87059-1-1.html?rss 既然已经搭建好环境了,那就对Android Studio中项目目录结构做个简单的了解了,这里以最 ...