• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
bobird的学习笔记
博客园    首页    新随笔    联系   管理    订阅  订阅
C#三种性能分析计时器介绍

要:本文介绍C#三种性能分析计时器:Stopwatch、Environment.TickCount、Win32 API函数QueryPerformanceCounter() 和 QueryPerformanceFrequency(),并提供了详细的示例供参考。

第一种方法:使用Stopwatch

class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Reset();
            sw.Start();          

            for (int i = 0; i < 11031400; i++)
            {
                InternalMethod();
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds.ToString());

       }

    private static void InternalMethod()
        {
        }
}

上面的代码重 复调用了方法100多万次,花的时间是7MS左右。而如果把for里的方法调用去掉,则只需要3MS左右,也就是说100多万次的调用要花费5MS左右的时间。
 

如果把for增加到1亿次,则需要500多MS。
 

第二种方法:使用Environment.TickCount

class Program
    {
        static void Main(string[] args)
        {
            long vTickCount = Environment.TickCount; //操作系统启动经过的毫秒数 即开机的时间

            for (int i = 0; i < 1103140; i++)
            {
                //InternalMethod();
            }        

            Console.WriteLine(Environment.TickCount - vTickCount);
        }
    }

第三种方法:高性能精确测量:Win32 API 使用QueryPerformanceCounter() 和 QueryPerformanceFrequency() 方法支持高精度计时。

       这些方法,比“标准的”毫秒精度的计时方法如 GetTickCount() 之类有高得多的精度。另一方面来说,在 C# 中使用“非托管”的 API 函数会有一定的开销,但比起使用一点都不精确的 GetTickCount() API 函数来说要好得多了。 

第一个函数 QueryPerformanceCounter() 查询任意时刻高精度计数器的实际值。第二个函数 QueryPerformanceFrequency() 返回高精度计数器每秒的计数值。为了获得某一代码段经历的时间,你需要获得代码段开始前和结束后这两个计时时刻的高精度计数器实际值。这两个值的差指出了代码段执行所经历的时间。

然后通过将差除以每秒计数值(高精度计时器频率),就可以计算经过的时间了。

duration = (stop - start) / frequency
经过时间 = (停止时间 - 开始时间) / 频率

 

需要关于 QueryPerformanceCounter 和 QueryPerformanceFrequency 的更多信息,请参阅 MSDN 文档。

下面的类实现了 QueryPerformanceCounter() 和 QueryPerformanceFrequency() API 函数的功能.

using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;

namespace Win32
{
    internal class HiPerfTimer
    {
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceCounter(
            out long lpPerformanceCount);

        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceFrequency(
            out long lpFrequency);

        private long startTime, stopTime;
        private long freq;

        // 构造函数
        public HiPerfTimer()
        {
            startTime = 0;
            stopTime  = 0;

            if (QueryPerformanceFrequency(out freq) == false)
            {
                // 不支持高性能计数器
                throw new Win32Exception();
            }
        }

        // 开始计时器
        public void Start()
        {
            // 来让等待线程工作
            Thread.Sleep(0);

            QueryPerformanceCounter(out startTime);
        }

        // 停止计时器
        public void Stop()
        {
            QueryPerformanceCounter(out stopTime);
        }

        // 返回计时器经过时间(单位:秒)
        public double Duration
        {
            get
            {
                return (double)(stopTime - startTime) / (double) freq;
            }
        }
    }
}

使用这个类很简单。只需要创建一个 HiPerfTimer 的实例,然后调用 Start() 开始计时,Stop() 停止计时。要获得经过的时间,调用 Duration() 函数即可。

参考下面的例子。

HiPerfTimer pt = new HiPerfTimer();     // 创建新的 HiPerfTimer 对象
pt.Start();                             // 启动计时器
Console.WriteLine("Test\n");            // 需要计时的代码
pt.Stop();                              // 停止计时器
Console.WriteLine("Duration: {0} sec\n", pt.Duration); // 打印需要计时部分代码的用时

文字出处:http://www.csharpwin.com/csharpspace/10719r7422.shtml

posted on 2013-04-23 15:57  bobird  阅读(2226)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3