Sleep in T-SQL / SQL Server script

Sometimes you need to make a script sleep for a short period of time, either for debugging purposes, or to make sure that something else has time to finish. To do this in T-SQL, you can use this command, which took me a lot of googling to find;

WAITFOR DELAY '00:00:00:50' -- 50ms delay
Advertisements

Benchmarking SQL Server operations

Sometimes you’re stuck trying to optimize a large stored procedure and the first step in optimizations is to figure out where the time is being spent. It’s not always where you expect, and going at it haphazardly doesn’t cut it.

The answer is of course benchmarking (timing), to figure out where the time is spent, and to figure out if your “fix” improved performance or not.

First of all, declare the variables you’ll need. Do this at the top of the the procedure/script that you’re benchmarking;

declare
  @totalTime datetime=GetDate(),
  @partTime datetime=GetDate()

Then drop in scripts like these throughout the code you’re benchmarking;

print ' Timing: [insert_descroption_here]'
print ' * Total time='+convert(varchar(10), datediff(ms, @totalTime,GetDate()))
print ' * Last Part='+convert(varchar(10), datediff(ms, @partTime,GetDate()))
set @partTime=GetDate()

Once you’ve found a block that takes an inordinate amount of time, either try to figure out how to optimize it, or insert more benchmarking points to pinpoint the actual culprit.

Here’s an example;

declare
  @totalTime datetime=GetDate(),
  @partTime datetime=GetDate()

-- Simulates actual script
WAITFOR DELAY '00:00:00:50' -- 50ms delay

print ' Timing: [Initiated]'
print ' * Total time='+convert(varchar(10), datediff(ms, @totalTime,GetDate()))
print ' * Last Part='+convert(varchar(10), datediff(ms, @partTime,GetDate()))
set @partTime=GetDate()

-- Simulates actual script
WAITFOR DELAY '00:00:10:00' -- 10s delay

print ' Timing: [Collected base data]'
print ' * Total time='+convert(varchar(10), datediff(ms, @totalTime,GetDate()))
print ' * Last Part='+convert(varchar(10), datediff(ms, @partTime,GetDate()))
set @partTime=GetDate()

-- Simulates actual script
WAITFOR DELAY '00:00:00:50' -- 50ms delay

print ' Timing: [Compute sums]'
print ' * Total time='+convert(varchar(10), datediff(ms, @totalTime,GetDate()))
print ' * Last Part='+convert(varchar(10), datediff(ms, @partTime,GetDate()))
set @partTime=GetDate()

print 'Done!'

This script produces this output;

Timing: [Initiated]

* Total time=50

* Last Part=50

Timing: [Collected base data]

* Total time=10043

* Last Part=9993

Timing: [Compute sums]

* Total time=10096

* Last Part=53

Done!

As you’ll notice, it’s the part up to “Collected base data” that’s slow, so that’s where you should start either benchmarking further or actually optimizing!