C# Diagnostic TimeClock class for debugging…

I like to clock certain operations, or group of operations to determine if a certain area of a function is taking a long time. It can be helpful to watch the progress of a function as well, with some useful eyeball metrics.

You can use the class below. Just create a blank class file and paste this in there.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CenterlineGroup.BPParts.BusinessLogic.Performance
{
public class TimeClock : IDisposable
{
private DateTime startTime = DateTime.Now;
private string operation = string.Empty;
public TimeClock(string Operation)
{
operation = Operation;
System.Diagnostics.Debug.WriteLine("Beginning operation: " + operation);
}

#region IDisposable Members

public void Dispose()
{
System.Diagnostics.Debug.WriteLine("Ending Operation: " + operation + ".It took " + (DateTime.Now - startTime).TotalMilliseconds + "ms to complete");
}

#endregion
}
}

To use it, just create the following style code:

 using (var clock = new TimeClock("Shipment: Add Freight Cost To Order"))
                {
                    DBAccess.BeginTransaction(IsolationLevel.Serializable);
                    Orders.AddFreightCostToOrder(request.OrderID, request.VendorID, request.ShippingAddressEntryID, request.ShippingCost);
                    DBAccess.CommitTransaction();
                }

Easy, eh? Simple, yet effective.

Leave a Reply

Your email address will not be published. Required fields are marked *