jpiccolo
jpiccolo

Reputation: 778

Wrapping methods generically to find performance?

I am trying to wrap a bunch of methods that interact with a API server to test how long each takes.

For instance I want to wrap these methods:

    public DCResultOfValidateSiteForUser ValidateSiteForUser(int UserId, int UserType, int SiteId)
    {
        return Service.ValidateSiteForUser(UserId, UserType, SiteId);
    }
    public DCResultOfIsSystemInStandby IsSystemInStandby()
    {
        return Service.IsSystemInStandby();
    }

Here is what I want to wrap around the above methods:

    public static T TestPerf<T>(Action action)
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        action();

        sw.Stop();

        StackTrace stackTrace = new StackTrace();
        StackFrame stackFrame = stackTrace.GetFrame(1);
        MethodBase methodBase = stackFrame.GetMethod();

        TextWriter tw = new StreamWriter("perfLog.txt", true);
        string s = String.Format("{0} {1}{2,15}", String.Format("{0:M/d/yyyy HH:mm:ss}", DateTime.Now), methodBase.Name, sw.Elapsed);
        tw.WriteLine(s);
        tw.Close();

        return default(T);
    }

However, since an Action returns void. I have then then do:

    public DCResultOfValidateSiteForUser ValidateSiteForUser(int UserId, int UserType, int SiteId)
    {
        TestPerf<DCResultOfValidateSiteForUser>(() => Service.ValidateSiteForUser(UserId, UserType, SiteId));
        return Service.ValidateSiteForUser(UserId, UserType, SiteId);
    }
    public DCResultOfIsSystemInStandby IsSystemInStandby()
    {
        TestPerf<DCResultOfIsSystemInStandby>(() => Service.IsSystemInStandby());
        return Service.IsSystemInStandby();
    }

What I want is:

    public DCResultOfIsSystemInStandby IsSystemInStandby()
    {
        return TestPerf<DCResultOfIsSystemInStandby>(() => Service.IsSystemInStandby());
    }

I do not want to have to put the stopwatch code into every method as there are 100's.

I appreciate any help that can be provided.

Thanks

Upvotes: 0

Views: 65

Answers (1)

Austin Salonen
Austin Salonen

Reputation: 50225

This should compile and not execute the methods twice:

public DCResultOfValidateSiteForUser ValidateSiteForUser(int UserId, int UserType, int SiteId)
{
    DCResultOfValidateSiteForUser result = null;
    TestPerf<DCResultOfValidateSiteForUser>(() => result = Service.ValidateSiteForUser(UserId, UserType, SiteId));
    return result;
}

Upvotes: 1

Related Questions