C# 中增加一个使用StopWatch记录方法执行时间的通用方法

发布时间 2023-11-24 11:11:15作者: Hello——寻梦者!

一 背景

在很多时候我们在进行代码排查的时候需要在日志中记录代码的执行时间从而方便我们进行代码运行效率的执行,我们在日志中准确记录方法的执行时间,这样方便我们进行代码的排查,下面分享一个我们常用的记录方式,方便使用,而且最重要的是代码高效和简单。

二 源码

public struct LogEntryExit : IDisposable
  {
    private readonly long entryTimestamp;
    private readonly string methodName;
    private readonly string source;
    private readonly string threadName;
    private bool isEntryExitEnabled;

    public LogEntryExit(string source)
    {
      this.isEntryExitEnabled = Log.IsCategoryEnabled(LogCategory.EntryExit);
      if (!this.isEntryExitEnabled)
      {
        this.entryTimestamp = 0L;
        this.source = (string) null;
        this.methodName = (string) null;
        this.threadName = (string) null;
      }
      else
      {
        this.entryTimestamp = Stopwatch.GetTimestamp();
        this.source = source;
        this.methodName = new StackFrame(1).GetMethod().Name;
        this.threadName = Global.GetThreadId();
        Log.Write(LogCategory.EntryExit, source, string.Format("TID {0} Entering {1}", (object) this.threadName, (object) this.methodName));
      }
    }

    void IDisposable.Dispose()
    {
      if (!this.isEntryExitEnabled)
        return;
      long num = (Stopwatch.GetTimestamp() - this.entryTimestamp) * 1000L / Stopwatch.Frequency;
      this.isEntryExitEnabled = false;
      Log.Write(LogCategory.EntryExit, this.source, string.Format("TID {0} Exiting {1} after {2} ms", (object) this.threadName, (object) this.methodName, (object) num));
    }
  }
}

三 使用方法

using(var logEntryExit=new LogEntryExit("Source"))
{
    // warp your source codes here
   ...
}