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

/// <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 @ 2020-07-20 18:11  wesson2019  阅读(153)  评论(0编辑  收藏  举报