Calculate code block execution time using “using”

Here’s an interesting way to calculate the execution time of a
code block:

private void SomeFunction() { using (
new TimedLog(Profile.UserName, Some
Function
)) { … … } }

You get an output like this:

6/14/2006
10:58:26 AM
4b1f6098-8c9d-44a5-93d8-e37394b6ef18
SomeFunction
9.578125

You can measure execution time of not only a function, but also
smaller blocks of code. Whatever is inside the “using” block, gets
logged.

Here’s how the TimedLog class do the work:

public class TimedLog
: IDisposable {
private
string _Message; private long _StartTicks; public TimedLog( string userName, string message) { this ._Message = userName +
t +
message; this ._StartTicks = DateTime.Now.Ticks; } #region IDisposable Members void IDisposable.Dispose() {
EntLibHelper.PerformanceLog(
this ._Message +
t +
TimeSpan.FromTicks(DateTime.Now.Ticks
this ._StartTicks).TotalSeconds.ToString()); }
#endregion }

We are using Enterprise Library to do the logging. You can use
anything you like on the Dispose method.

The benefit of such log is, we get a tab delimited file which we
can use to do many types of analysis using MS Excel. For example,
we can generate graphs to see how the performance goes up and down
during peak hours and non peak hours. We can also see whether there
are high response times or not and what is the pattern. All these
gives us valuable indications where the bottle-neck is. You can
also find out which calls take most of the time by doing sort on
the duration column.

3 thoughts on “Calculate code block execution time using “using””

Leave a Reply