我审查并同意所有建议。但是想分享一个执行时间记录器的通用实现,我们不想多次实现秒表逻辑,但仍想测量多个方法的执行时间。
不以通用方式实现记录器的主要原因是 - 方法执行在 stopwatch.Start() 和 stopwatch.Stop() 之间,我们也可能需要执行后的方法结果以进行进一步处理。
因此,为了解决这个问题,我创建了以下示例实现,其中单独记录执行时间,而不将其与实际方法流混合。
public static class Helper
{
public static T Time<T>(Func<T> method, ILogger log)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
var result = method();
stopwatch.Stop();
log.Info(string.Format("Time Taken For Execution is:{0}", stopwatch.Elapsed.TotalMilliseconds));
return result;
}
}
public class Arithmatic
{
private ILogger _log;
public Arithmatic(ILogger log)//Inject Dependency
{
_log = log;
}
public void Calculate(int a, int b)
{
try
{
Console.WriteLine(Helper.Time(() => AddNumber(a, b), _log));//Return the result and do execution time logging
Console.WriteLine(Helper.Time(() => SubtractNumber(a, b), _log));//Return the result and do execution time logging
}
catch (Exception ex)
{
_log.Error(ex.Message, ex);
}
}
private string AddNumber(int a, int b)
{
return "Sum is:" + (a + b);
}
private string SubtractNumber(int a, int b)
{
return "Subtraction is:" + (a - b);
}
}
public class Log : ILogger
{
public void Info(string message)
{
Console.WriteLine(message);
}
public void Error(string message, Exception ex)
{
Console.WriteLine("Error Message:" + message, "Stacktrace:" + ex.StackTrace);
}
}
public interface ILogger
{
void Info(string message);
void Error(string message, Exception ex);
}
调用部分:
static void Main()
{
ILogger log = new Log();
Arithmatic obj = new Arithmatic(log);
obj.Calculate(10, 3);
Console.ReadLine();
}