Category Archives: Performance Tuning

Stored Procedure or Query Execution Times

Today we will see different ways to calculate the execution times of a SQL Query.

Typically it happens that we are tasked to performance tune certain queries to find out which queries or procedures are taking more time than expected. Here are 3 choices one could follow:

1. Using SQL Profiler: Look for the events SQL:BatchCompleted, RPC:completed and then capture the exectution times in Milliseconds.

2. Using Getdate():

1
2
3
4
5
6
7
8
DECLARE @START datetime, @END datetime, @timediffinMS INT
SELECT @START = getdate()
SELECT *  FROM sys.syscomments
-- OR
EXEC SP_WHO2
SELECT @END = getdate()
SELECT @timediffinMS = datediff (ms, @START, @END)
SELECT @timediffinMS -- this can be put in a table to analyze the time taken.

3. SET Command:

1
2
3
SET STATISTICS TIME ON
SELECT * FROM sys.sysobjects
SET STATISTICS TIME OFF

Look for the last total CPU time and CPU elapsed times.

Note: Sometimes when you run these queries or procedures they remain in cache and hence run fast next time they are run, so please make sure to free up procedure cache using DBCC Dropcleanbuffers or DBCC Freeproccache or DBCC Freesystemcache (warning!! it has its own disadvantages of using above commands in production systems as they will remove all plans from plancache and all procedures will take more time or rarely less time to execute, so use with caution). The issue is that all procs get affected and not just the single proc you are trying to tune.

Also try to use CLIENT statistics option in SSMS that will average out based on a number of runs giving accurate picture avg. running time of the query.