PDA

View Full Version : Better code for this ? (profiling advice)



Thibaut
04-12-2006, 12:46 PM
Hi!

while developing some ldap authentication routine, I wanted to measure the time taken by the authentication call. I thought going AOP would be rather handy and non-obstrusive on the code I want to profile.

I came up with the following stuff - could anyone with more Spring AOP experience review that ? Any feedback welcome.

the advice:



public class ProfilingAdvice : IMethodInterceptor
{
private static readonly ILog log = LogManager.GetLogger(typeof(ProfilingAdvice));

public object Invoke(IMethodInvocation invocation)
{
DateTime startTime = DateTime.Now;
try
{
return invocation.Proceed();
}
finally
{
log.Info(string.Format("{0}.{1} call took {2}",invocation.Method.DeclaringType.Name,invocation.M ethod.Name,DateTime.Now-startTime));
}
}
}


the helper to return a proxified instance:



private static object BuildProfilingProxy(object originalObject)
{
ProxyFactory factory = new ProxyFactory(originalObject);
factory.AddAdvice(new ProfilingAdvice());
return factory.GetProxy();
}


and sample code usage



[Test, Explicit]
public void BenchmarkLDAPCall()
{
BasicConfigurator.Configure();

ILDAPAuthenticationProvider provider = new DirectoryServicesAuthenticationProvider();

provider = (ILDAPAuthenticationProvider)BuildProfilingProxy(p rovider);

Assert.IsTrue(provider.Authenticate("myldaphost", "cn=mylogin,o=mycompany");
}


cheers

Thibaut Barrère

Bruno Baia
04-12-2006, 01:33 PM
Bonjour Thibaut,

The AOP part seems good.
But if you need more precision, u can use ticks :



long start = DateTime.Now.Ticks;
// Code
long end = DateTime.Now.Ticks;


If you are working on .NET 2.0 framework, you should use the new System.Diagnostics.StopWatch class :



Stopwatch sw = Stopwatch.StartNew();
try
{
return invocation.Proceed();
}
finally
{
sw.Stop();
// sw.ElapsedMilliseconds, sw.ElapsedTicks, etc...
}



- Bruno

Thibaut
04-12-2006, 01:44 PM
Hi Bruno

thanks for the review, and good point about the accuracy (well in my case the server takes 10+ seconds to reply for the moment so I'm accurate enough)

cheers