Is it possible to calculate the execution time of a method in C # with attributes?

Is there a C # attribute (for a method) to calculate the runtime of this method? Is there another way?

+4
source share
6 answers

If you want to write some kind of test code to profile various functions or parts of them, you should use System.Diagnostics.Stopwatch to track elapsed time. Like this:

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)) } 

If this is the more general thing you want to do (i.e. find out which parts of the program are slow), then use the profiler as some of the other answers suggest.

+2
source

You can use Aspect Oriented programming for this. Have a look at this example from PostSharp: http://www.sharpcrafters.com/solutions/performance

The trick here is to determine the behavior that will be introduced into your code at compile time. One use case is to add time to the methods you need.

+5
source

There is another way: you can use VS Profiler to check how many times and how long the method takes.

or you can use a third-party library that uses attributes to profile performance, see this related section. What are good .NET profiles?

+4
source

You can use Timer , start it before calling the function, and then stop it after the method finishes. Then print the time in your preferred form!

OR

If you don't want to write manual code, check out Visual Studio Profilers or SO, the best profilers .

+3
source

Just like a pie:

+1
source

Something like that:

  var oldTime = DateTime.Now; //your code here var resultTimeSpan = DateTime.Now - oldTime; 
0
source

All Articles