是否可以使用属性计算C#中方法的执行时间?

Bas*_*mme 5 c# performance attributes

是否有C#属性(用于方法)来计算此方法的执行时间?还有另外一种方法吗?

Bek*_*pov 5

还有其他方法:您可以使用VS Profiler来检查particuler方法执行了多少次和多长时间。

或者您可以使用属性来分析性能的第 3 方库,请参阅相关主题What Are Some Good .NET Profilers?


Run*_*tad 5

您可以使用面向方面编程来执行此操作.从PostSharp看这个例子:http://www.sharpcrafters.com/solutions/performance

这里的技巧是定义在编译时注入代码的行为.一个用例是为您需要的方法添加时序.


Rus*_*est 3

如果您想编写一些测试代码来分析各种函数或其部分,您可以使用 System.Diagnostics.Stopwatch跟踪经过的时间。像这样:

public void DoSomething(){
  Stopwatch stopWatch = new Stopwatch();
  stopWatch.Start();

  //stuff you want to time

  stopWatch.Stop();

  System.Console.Writeln(String.Format("Total Ticks: {0}", stopWatch.ElapsedTicks))
}
Run Code Online (Sandbox Code Playgroud)

如果这是您想做的更一般的事情(即找出程序的哪些部分很慢),那么请使用分析器,就像其他一些答案所建议的那样。