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
)) { … … } }

You get an output like this:

10:58:26 AM

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

Here’s how the TimedLog class do the work:

public class TimedLog
: IDisposable {
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() {
this ._Message +
t +
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