Tôi đã xem xét và đồng ý với tất cả các đề xuất. Nhưng muốn chia sẻ một triển khai chung cho trình ghi thời gian thực thi mà chúng ta không muốn thực hiện logic Đồng hồ bấm giờ nhiều lần nhưng vẫn muốn đo thời gian thực hiện cho nhiều phương thức.
Lý do chính để không triển khai trình ghi theo cách thức chung là - thực hiện phương thức nằm giữa đồng hồ bấm giờ.Start() và stopwatch.Stop() cũng có thể yêu cầu kết quả phương pháp sau khi thực hiện xử lý tiếp.
Vì vậy, để giải quyết vấn đề này tôi tạo ra sau khi thực hiện mẫu, nơi thực hiện thời gian đăng nhập một cách riêng biệt mà không trộn nó với dòng phương pháp thực tế.
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);
}
Calling Phần:
static void Main()
{
ILogger log = new Log();
Arithmatic obj = new Arithmatic(log);
obj.Calculate(10, 3);
Console.ReadLine();
}
Nguồn
2016-09-01 18:02:54
nếu bạn thiết lập timer.stop(); sau khi Start() là bình thường. Khi nào cần dừng hẹn giờ? Khi chức năng kết thúc? –
tại sao không StopWatch? (http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) – VJAI
Bản sao có thể có của [Đo thời gian thực thi mã] (https://stackoverflow.com/questions/16376191/measuring- code-execution-time) –