Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count time elapsed for a method with an utility class

Tags:

c#

.net

asp.net

I am writing a very simple utility class with the aim to measure the time executed for any method passed in (of any type).

In my case Membership.ValidateUser(model.UserName, model.Password) return bool so I get an exception.

I would like if would be possible write a utililty class of this type an a sample of code on how to fix it. Does it make sense use dynamic in stead of action?

Tracing.Log(Membership.ValidateUser(model.UserName, model.Password), "Membership.ValidateUser");

public static class Tracing
        {
            public static void Log(Action action, string message)
            {
                // Default details for the Log
                string sSource = "TRACE";
                string sLog = "Application";

                // Create the Log
                if (!EventLog.SourceExists(sSource))
                    EventLog.CreateEventSource(sSource, sLog);

                // Measure time Elapsed for an Action
                Stopwatch stopwatch = Stopwatch.StartNew();
                action();
                stopwatch.Stop();
                TimeSpan timeElapsed = stopwatch.Elapsed;

                // Write the Log
                EventLog.WriteEntry(sSource, "TIME-ELAPSED: " + timeElapsed .ToString() + message, EventLogEntryType.Warning, 234);
            }
        }
like image 295
GibboK Avatar asked Mar 13 '13 12:03

GibboK


1 Answers

Your current code tries to execute ValidateUser and use the result as the method argument. You want to pass in an action without first executing ValidateUser.

You just need to convert your method call to use a lambda expression to create a delegate:

Tracing.Log(() => Membership.ValidateUser(model.UserName, model.Password), 
            "Membership.ValidateUser");

(Dynamic typing wouldn't affect this at all.)

Note that timing a single method execution is often going to give you very noisy results, unless it's a reasonably long method call. Usually to benchmark a single method you'd want to execute the method many times, until you've spent a reasonably significant amount of time executing it. Using Stopwatch helps, but it doesn't get past the fact that your method may require very few ticks to complete, and if the thread is pre-empted, that will have a disproportionate effect on the results.

EDIT: I'm assuming that you want to use this purely for benchmarking. If you're trying to do this tracing in your real application, you'll want a less invasive approach. Look at Mini-MVC-Profiler for example.

like image 186
Jon Skeet Avatar answered Oct 23 '22 19:10

Jon Skeet