Friday, October 17, 2008

Easily Determine Execution Time

Most everyone has gone through at one point in time or another, and tried to determine which of two statements, would be quicker to execute. Usually this involves doing two DateTime.Now() function calls and then doing a DateDiff, and having to search the internet for how to format the output correctly.

My coworker was exploring the System.Diagnostics namespace and stumbled upon the Stopwatch class which makes solving this issue much easier. Observe the snippet at the bottom of this post. Not that you'd ever want to do this particular example, but look at the power it gives you.

In this example, I'm wanting to see how long it takes to perform the GetEditLevel() function, while allowing the user to read the name of the customer. By starting the stopwatch only after the message box has been closed, and stopping it after the function has finished executing, it will keep track of the total number of ticks, then you can call ElapsedMilliseconds to get the total amount of time.

I think its a beautiful layer of abstraction.


int totalEditLevel = 0;
System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew();
foreach(CustomerInfo cust in CustomerList.GetCustomerListAll()){
if(watch.IsRunning){
//First time, Reset it
watch.Reset();
}
MessageBox.Show("Customer is " + cust.CustName);
watch.Start();
totalEditLevel += cust.GetEditLevel();
watch.Stop();
}
MessageBox.Show("Total Seconds was " + ((double)watch.ElapsedMilliseconds / 100.0).ToString());


No comments: