对一段代码计时同查通常有三种方法。最简单就是用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. 使用JMeter进行简单的压力测试

    一.压力测试 顾名思义:压力测试,就是  被测试的系统,在一定的访问压力下,看程序运行是否稳定/服务器运行是否稳定(资源占用情况). 比如: 2000个用户同时到一个购物网站购物,这些用户打开页面的速 ...

  2. CSS之伪类

    1. :link                     向未被访问的链接添加样式 :visited                向已被访问的链接添加样式 :hover               ...

  3. JSTL 自定义标签

    编写描述标签的tld文件,把这个文件放到web-inf/目录下,才能在jsp页面上调用自定义的标签 package test.yz; import java.io.IOException; impor ...

  4. MAC使用MAMP构建自签名HTTPS环境

    一.生成HTTPS自签名证书 1.下载最新的openssl的安装包,下载地址:https://www.openssl.org/source/ 2.解压最新版openssl,可以直接双击使用MAC自带的 ...

  5. MVVM与Backbone demo

    MVVM https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel

  6. Liunx下的系统负荷

                uptime命令回显中的load average所表示的意思和w命令相似,都是表示过去的1分钟.5分钟和15分钟内进程队列中的平均进程数量. 这里需要注意的是load aver ...

  7. SLP的模块结构

    SLP的模块结构 在开发初期,拟将SLP分为5个模块: 基础练习模块 特定歌曲难点练习模块 玩家能力测试模块 全局设置模块 玩家信息模块 基础练习模块 这里提供可控类型.可控长度.可控BPM的练习套餐 ...

  8. 自定义cell侧滑删除

    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { return Y ...

  9. android自定义拍照

    调用系统相机,然后在自己的surfaceview上预览,拍照,不废话,直接上源码 package com.example.customecamera; import java.io.File; imp ...

  10. iOS之在webView中引入本地html,image,js,css文件的方法 - sky//////////////////////////////////////ZZZZZZZZZZZZZZZ

    iOS之在webView中引入本地html,image,js,css文件的方法   2014-12-08 20:00:16CSDN-sky_2016-点击数:10292     项目需求 最近开发的项 ...