C#三种性能分析计时器介绍

来源:互联网 发布:torrent下载软件 编辑:程序博客网 时间:2024/06/06 05:45


第一种方法:使用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); // 打印需要计时部分代码的用时

以上介绍的就是C#三种性能分析计时器,希望对你有所帮助。
 

0 0
原创粉丝点击