精确获取一个方法的执行时间

来源:互联网 发布:flash for mac最新版 编辑:程序博客网 时间:2024/06/05 08:17

 1、有时候需要一个方法执行所需的时间,简单的使用DateTime.Now不够正确。

在网上搜了下:

可以使用系统的性能计数器来实现:

 

    [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
    static extern bool QueryPerformanceCounter(ref long count);

 

    [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
    static extern bool QueryPerformanceFrequency(ref long count);

 

    // 开始计数

        long Fcount = 0;
        long Scount = 0;
        long freq = 0;
        double result = 0;

        QueryPerformanceFrequency(ref freq);
        QueryPerformanceCounter(ref Fcount);

 

        // 这里是你执行的方法

 

    // 计算执行的时间。

        QueryPerformanceCounter(ref Scount);
        Fcount = Scount - Fcount;
        result = (double)(Fcount) / (double)(freq);

        Response.Write(string.Format("耗时: {0}秒",result));

 

 

可这还有一个问题,不行动态绑定方法,如果动态执行方法的话,性能上又有损失,

所以只能尽量少使用,关键时用一下。。

 

 

原创粉丝点击