0

我需要记录各种方法所花费的时间,到目前为止我正在使用 Stopwatch 的企业服务器应用程序中的代码块,我实现的示例代码如下:

var sw = new Stopwatch();
sw.Start();
DoSomething();
sw.Stop();
logManager.LogInformation(String.Format("Time taken by DoSomething function is {0} ms.", sw.ElapsedMilliseconds));

我在很多 .cs 文件的很多地方都这样写,我只是想通过编写一种常用方法或扩展来减少这种手动工作来测量所用时间。为此,我想用时间测量方法来包装我的实际方法,例如:

long elapsedMilliseconds = ExecuteAndGetTimeTaken(this.DoSomething());

或通用扩展方法,如

long elapsedMilliseconds = this.DoSomething().GetTimeTaken();

如果该方法也记录带有时间的消息,那就太好了,例如

long elapsedMilliseconds = ExecuteAndGetTimeTaken(this.DoSomething(),logManager,message);

如何编写通用类/方法或扩展来解决目的?

4

2 回答 2

6

这应该这样做:

void ExecuteAndMeasureTimeTaken(Action action, string message)
{
    if(action == null) throw new ArgumentNullException();
    else
    {
        var sw = new Stopwatch();
        sw.Start();

        action();

        sw.Stop(); 

        LogMessage(message , sw.ElapsedMilliseconds);
    }
}

像这样称呼它:

logManager.ExecuteAndMeasureTimeTaken(() => GC.Collect(), "Time taken by GC after each Listning is {0} ms.");

它真的需要一个 LogManager 参数吗?

如果是这样,您可以将其添加到您的 LogManager 本身。

于 2013-05-20T11:03:35.597 回答
2

I created once a short class, which can be used in a using statement. one other advantage is, that if an exception is thrown, also the time is measured

/// <summary>
/// Provides a easy to use timer. 
/// Usage
/// using(new DiagnosticTimer())
/// {
///     // do anything
/// }
/// </summary>
public class DiagnosticTimer : IDisposable
{
    public System.Diagnostics.Stopwatch StopWatch { get; protected set; }
    public string Message { get; set; }

    public DiagnosticTimer()
    {
        Message = "Diagnostic Timer at " + new System.Diagnostics.StackTrace().GetFrame(1).ToString();
        StopWatch = new System.Diagnostics.Stopwatch();
        StopWatch.Start();
    }
    public DiagnosticTimer(string Message)
    {
        this.Message = Message;
        StopWatch = new System.Diagnostics.Stopwatch();
        StopWatch.Start();
    }

    public void Dispose()
    {
        StopWatch.Stop();
        System.Diagnostics.Trace.WriteLine(Message + StopWatch.Elapsed.ToString());
    }

}
于 2013-05-20T11:41:31.883 回答