高性能 计时器:统计功能耗时

/// <summary>
/// 高性能 计时器:统计功能耗时ms
/// </summary>
public class HiPerfTimer
{
    [System.Security.SuppressUnmanagedCodeSecurity]
    [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
    private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
    [System.Security.SuppressUnmanagedCodeSecurity]
    [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
    private static extern bool QueryPerformanceFrequency(out long lpFrequency);
    private long _startTime;
    private long _stopTime;
    /// <summary>
    /// CPU频率,每秒时钟周期
    /// </summary>
    private readonly long _freq;
    public HiPerfTimer()
    {
        _startTime = 0;
        _stopTime = 0;
        if (false == QueryPerformanceFrequency(out _freq))
        {
            // 不支持高性能计数器
            throw new System.ComponentModel.Win32Exception();
        }
    }
    public void Start()
    {
        System.Threading.Thread.Sleep(0);
        QueryPerformanceCounter(out _startTime);
    }
    public void Stop()
    {
        QueryPerformanceCounter(out _stopTime);
    }
    /// <summary>
    /// 间隔(ms)
    /// </summary>
    public double Duration=> (double)(_stopTime - _startTime) / _freq * 1000;
    
    /// <summary>
    /// 统计执行方法体的时间(ms)
    /// </summary>
    /// <param name="action"></param>
    /// <returns></returns>
    public static double Execute(Action action, string msg = "")
    {
        var timer = new HiPerfTimer();
        timer.Start();
        action();
        timer.Stop();
        if (!string.IsNullOrWhiteSpace(msg))
        {
            Console.Write($"{DateTime.Now:yyyy-MM-dd HH:mm:ss,fff} [{Thread.CurrentThread.ManagedThreadId}]:");
            Console.Write(string.Format("{0} cost - ", msg));
            var oldColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write(timer.Duration);
            Console.ForegroundColor = oldColor;
            Console.WriteLine(string.Format(" ms"));
        }
        return timer.Duration;
    }
}
var time = HiPerfTimer.Execute(() =>
{
    // TODO
});

Console.WriteLine($"Timer: {time} ms");

posted @   wesson2019  阅读(159)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示