Using SPMonitoredScope to monitor performance of your code
Posted
Friday, May 28, 2010 10:43 AM
by
CoreyRoth
As a SharePoint developer, I’m sure you were excited to see the Developer Dashboard. It’s a great way to see what’s going ton with the performance of a page. Did you know you can add your own performance monitors to it though? It’s actually quite easy with the SPMonitoredScope class. Simply, put the code in question that you want to monitor inside a using block and SPMonitoredScope does the rest. For today’s example, I want to monitor the performance of some code that inserts an item into a list. Here is what it looks like.
using (SPMonitoredScope monitoredScope = new SPMonitoredScope("My Monitored Scope"))
{
// put code to monitor performance on here
SPList testList = site.Lists.TryGetList("Test List");
if (testList != null)
{
SPListItem listItem = testList.Items.Add();
listItem["Title"] = string.Format("Test Item {0}", Guid.NewGuid().ToString());
listItem["City"] = "Somewhere";
listItem["Quantity"] = 3;
listItem.Update();
}
}
I just give the SPMonitoredScope a name and put my code inside the using block. Don’t you just love TryGetList? This code assumes I already have access to a SPWeb. In this case I am running it inside a Visual Web Part and I left out some of the other code involved. When we view the page and have the developer dashboard running it looks like this.
There you can see My Monitored Scope in the list at a runtime of 2442.77 ms. Wow, that is some poorly performing code. It would be nice if we could get some more detail. Well what is cool is that you can actually nest using blocks to get performance data at a more granular level.
using (SPMonitoredScope monitoredScope = new SPMonitoredScope("My Monitored Scope"))
{
SPList testList;
using (SPMonitoredScope getListMonitor = new SPMonitoredScope("Get List"))
{
testList = site.Lists.TryGetList("Test List");
}
using (SPMonitoredScope addListItemMonitor = new SPMonitoredScope("Add List Item"))
{
if (testList != null)
{
SPListItem listItem = testList.Items.Add();
listItem["Title"] = string.Format("Test Item {0}", Guid.NewGuid().ToString());
listItem["City"] = "Somewhere";
listItem["Quantity"] = 3;
listItem.Update();
}
}
}
Now, I have added blocks to track the time it takes to get an instance of the list as well as the time it takes to add the item.
From here we can see that the bulk of the time spent is on adding the list item. Almost a full two seconds. You have to love virtual machines. :-) I think this class is very powerful and I can see it quickly becoming a best practice to having one or more SPMonitoredScope wrapped around the code you are executing. Start using it today!