3

I am trying to think on the best way to enter a statistic and some kind of logging in to my program. 1. does anyone have a good article about statistics to implement in a program ?
2. can i create an attribute to have before some method that call on a timer to measure the time it took to run ?for example

class A
{
  [RunTimer]
  public void Foo()
  {
     // do stuff
  }
}

EDIT
well we want to have the opportunity to have the possibility of controlling the statistics during run time, not just ob dev or QA time.

guyl
  • 2,158
  • 4
  • 32
  • 58
  • My question for code review, here might help. You can use the `IDispose` interface to make a neat solution: http://stackoverflow.com/questions/6410569/speeding-up-performance-monitoring-code – George Duckett Jul 04 '11 at 09:39
  • 1
    profiler, can you direct me ? – guyl Jul 04 '11 at 10:11

4 Answers4

6

One option is to make a higher-order function that will time a target function and log the results:

public static class TimingExtensions
{
    public static Func<R> Time<R>(this Func<R> target, Action<string> logger)
    {
        return delegate
        {
            System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();

            s.Start();

            R value = target();

            s.Stop();

            logger("Function '" + target.Method.Name + "' elapsed ms: " + s.ElapsedMilliseconds); 

            return value;
        }; 
    }
}

But if you need to do some heavy performance testing then there are frameworks out there for that, as well.

Sean Thoman
  • 7,429
  • 6
  • 56
  • 103
4

Performance Counters are your friends. .NET Instrumentation Workshop is an awesome article that walks you step by step through the process.

Once you have your algos, you can instrument all sorts of statistics with them.

Plus, counters can be controlled at runtime in two ways:

  • Change whether your app updates the perf counters via a config file switch
  • Change what updates you track via PerfMon

This way, you're not tied to just dev code, but you could also use them in production code. Of course, you may not want them all constantly running, which is where allowing the configuration file switch would come in handy.

Gustavo Mori
  • 8,319
  • 3
  • 38
  • 52
4

You are looking for a profiler: Any decent C# profilers out there?

(for example: http://www.red-gate.com/products/dotnet-development/ants-performance-profiler/)

Community
  • 1
  • 1
RvdK
  • 19,580
  • 4
  • 64
  • 107
2

If you're willing to use the PostSharp library, then you could use some of their AOP-based performance counter examples.

Peter K.
  • 8,028
  • 4
  • 48
  • 73