PostSharp – Simple profiling aspect

I recently came across an example of how to use PostSharp to create a profiling aspect (source).

The following example takes advantage of the OnMethodBoundaryAspect class.

    [ProfilerAspect(AttributeExclude = true)]
    public class ProfilerAspect : OnMethodBoundaryAspect
        public override void OnEntry(MethodExecutionArgs args)
            args.MethodExecutionTag = Stopwatch.StartNew();

        public override void OnExit(MethodExecutionArgs args)
            Stopwatch sw = (Stopwatch)args.MethodExecutionTag;

            string output = string.Format("{0} Executed in {1} milliseconds",
                                args.Method.Name, sw.ElapsedMilliseconds);


Apply the aspect on the assembly:

[assembly: ProfilerAspect()]

If you choose to apply the aspect on the entire assembly, set the AttributeExclude to true on the aspect itself.
Don’t forget to reference the PostSharp assembly…and it’s done.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s