How to calculate time for method execution?

K

Karl Seguin

There are a number of ways...is this simply for testing purposes? You can
turn tracing on in your page directive <%@ Page Trace="True" ...%> and do
something like:

Page.Trace.Write("START");
CallYourFunctionHere();
Page.Trace.Write("END");

and at the bottom of the page you'll see the START and END as well as how
long it took.


Alternatively, you can profile your code using a tool such as Red-Gate's
(www.red-gate.com) ANTs Profiler (full 14 day free trial)...or there are
other free ones...which should really give you deep analysis.


Finally, if you need this in more of a production scenerio, you can use
something like:

DateTime start = DateTime.Now;
CallYourFunctionHere();
TimeSpan ts = DateTime.Now.Subtract(start);
//use ts.TotalMilliseconds to get the total amount of time it took..


Karl
 
J

James Moore

For simple scenarios, I use:


public class CodeTimer : IDisposable
{
public CodeTimer (string msg)
{
_msg = msg;
if (_msg.Length > 0)
_msg += " ";
++_depth;
}

public CodeTimer () : this ("")
{
}

public void Dispose ()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}

public void Dispose (bool disposing)
{
if (disposing)
{
--_depth;
string indent = new String (' ' , _depth * 4);
double totalSeconds = (DateTime.Now - _start).TotalSeconds;
Debug.WriteLineIf (totalSeconds > 0, indent + _msg + string.Format
("Elapsed time: {0}", totalSeconds));
}
}

~CodeTimer ()
{
this.Dispose (false);
}

DateTime _start = DateTime.Now;
string _msg;
static int _depth = 0;
}


Use it like so:

using (Com.Banshee.Utilities.CodeTimer c = new
Com.Banshee.Utilities.CodeTimer ("in CreateAdapters")) {

do stuff

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top