我審查並同意所有建議。但是想要共享一個執行時間記錄器的通用實現,我們不想多次實現Stopwatch邏輯,但仍想測量多個方法的執行時間。
不以通用方式實現記錄器的主要原因是 - 方法執行在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();
}
如果設置timer.stop()的時間;開始()後正常。何時需要停止定時器?功能完成後? – 2012-04-11 13:44:24
爲什麼不是秒錶? (http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) – VJAI 2012-04-11 13:46:41
[測量代碼執行時間]的可能重複(https://stackoverflow.com/questions/16376191/measuring-代碼執行時間) – 2017-06-19 03:37:49