高分辨率计时器

以下代码来自http://blogs.gotdotnet.com/ZHANBOS/commentview.aspx/fe108056-bf72-4029-accf-22ccb9e7bb7d
其原理是通过 P/Invoke,调用Win32的高分辨率性能计数器

public class HighResolutionTimer
{
    private long start;
    private long stop;
    private long frequency;

    public HighResolutionTimer()
    {
        QueryPerformanceFrequency (ref frequency);
    }

    public void Start ()
    {
        QueryPerformanceCounter (ref start);
    }

    public void Stop ()
    {
        QueryPerformanceCounter (ref stop);
    }

    public float ElapsedTime
    {
        get{
            float elapsed = (((float)(stop - start)) / ((float) frequency));
            return elapsed;
        }
    }

    [System.Runtime.InteropServices.DllImport("KERNEL32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
    private static extern bool QueryPerformanceCounter( [In, Out] ref long performanceCount);
    [System.Runtime.InteropServices.DllImport("KERNEL32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
    private static extern bool QueryPerformanceFrequency( [In, Out] ref long frequency);
}

To illustrate the use of this class, check the code below.

    HighResolutionTimer timer = new HighResolutionTimer();
    timer.Start();
    //Perf Test
    timer.Stop();
    Console.WriteLine(timer.ElapsedTime);

关于此方法的注意事项http://support.microsoft.com/default.aspx?scid=kb;zh-cn;327809

类似代码可以在网上方便找到,有空时利用此方法来测量一下.net的各种操作的性能,仅供个人参考资料之用

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值