开发者

Time benchmark decorator in C#

I would like (in an ELEGANT way) to use some custom method attribute which will give me this:

When I call such a method foo(), in some attribute I'll have the elapsed time (how long the method call lasted).

开发者_运维百科

How can I do it in C#? Reflections?

Thank you in advance. James


C# doesn't offer this out of the box. You have a few choices:

  1. Use some external profiler (I think higher editions of VS have one integrated)
  2. Use an AOP framework. For example Postsharp rewrites your IL in an after build step to introduce prolog/epilog code based on attributes.


What's wrong with the StopWatch class? I use it regularly for profiling general timings in critical code. If that's not enough, I'll switch to ANTS (or dotTrace).


Action<Action> elegantBenchmark = (body) =>
{
    var startTime = DateTime.Now;
    body();
    Console.WriteLine(DateTime.Now - startTime);
};

elegantBenchmark(DoWork);

P.S. PostSharp will do the work as you want it to be done.


There is no way to intercept a plain old method call in C#. You would have to post(pre)-process your C# code (like with PostSharp) to really achieve this.

Alternatively, you could write a benchmarking method that takes a lambda to time a chunk of code, but this is obviously not a true decorator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜