This article is contributed. See the original author and article here.

Have you ever wondered why some SQL queries take forever to execute, even when the CPU usage is relatively low? In our latest support case, we encountered a fascinating scenario: A client was puzzled by a persistently slow query. Initially, the suspicion fell on CPU performance, but the real culprit lay elsewhere. Through a deep dive into the query’s behavior, we uncovered that the delay was not due to CPU processing time. Instead, it was the sheer volume of data being processed, a fact that became crystal clear when we looked at the elapsed time. The eye-opener was our use of SET STATISTICS IO, revealing a telling tale: SQL Server Execution Times: CPU time = 187 ms, elapsed time = 10768 ms. Join us in our latest blog post as we unravel the intricacies of SQL query performance, emphasizing the critical distinction between CPU time and elapsed time, and how understanding this can transform your database optimization strategies.


 


Introduction


In the realm of database management, performance tuning is a critical aspect that can significantly impact the efficiency of operations. Two key metrics often discussed in this context are CPU time and elapsed time. This article aims to shed light on these concepts, providing practical SQL scripts to aid database administrators and developers in monitoring and optimizing query performance.


 


What is CPU Time?


CPU time refers to the amount of time for which a CPU is utilized to process instructions of a SQL query. In simpler terms, it’s the actual processing time spent by the CPU in executing the query. This metric is essential in understanding the computational intensity of a query.


 


What is Elapsed Time?


Elapsed time, on the other hand, is the total time taken to complete the execution of a query. It includes CPU time and any additional time spent waiting for resources (like IO, network latency, or lock waits). Elapsed time gives a more comprehensive overview of how long a query takes to run from start to finish.


 


Why Are These Metrics Important?


Understanding the distinction between CPU time and elapsed time is crucial for performance tuning. A query with high CPU time could indicate computational inefficiency, whereas a query with high elapsed time but low CPU time might be suffering from resource waits or other external delays. Optimizing queries based on these metrics can lead to more efficient use of server resources and faster query responses.


 


Practical SQL Scripts


Let’s delve into some practical SQL scripts to observe these metrics in action.


Script 1: Table Creation and Data Insertion


 


 


 

CREATE TABLE EjemploCPUvsElapsed (
    ID INT IDENTITY(1,1) PRIMARY KEY,
    Nombre VARCHAR(5000),
    Valor INT,
    Fecha DATETIME
);

DECLARE @i INT = 0;
WHILE @i < 200000
BEGIN
    INSERT INTO EjemploCPUvsElapsed (Nombre, Valor, Fecha)
    VALUES (CONCAT(REPLICATE('N', 460), @i), RAND()*(100-1)+1, GETDATE());
    SET @i = @i + 1;
END;

 


 


 


This script creates a table and populates it with sample data, setting the stage for our performance tests.


Script 2: Enabling Statistics


Before executing our queries, we enable statistics for detailed performance insights.


 


 


 

SET STATISTICS TIME ON;
SET STATISTICS IO ON;

 


 


 


Script 3: Query Execution


We execute a sample query to analyze CPU and elapsed time.


 


 


 

SELECT *
FROM EjemploCPUvsElapsed
ORDER BY NEWID() DESC;

 


 


 


Script 4: Fetching Performance Metrics


Finally, we use the following script to fetch the CPU and elapsed time for our executed queries.


 


 


 

SELECT 
    sql_text.text,
    stats.execution_count,
    stats.total_elapsed_time / stats.execution_count AS avg_elapsed_time,
    stats.total_worker_time / stats.execution_count AS avg_cpu_time
FROM 
    sys.dm_exec_query_stats AS stats
CROSS APPLY 
    sys.dm_exec_sql_text(stats.sql_handle) AS sql_text
ORDER BY 
    avg_elapsed_time DESC;

 


 


 


Conclusion


Understanding and differentiating between CPU time and elapsed time in SQL query execution is vital for database performance optimization. By utilizing the provided scripts, database professionals can start analyzing and improving the efficiency of their queries, leading to better overall performance of the database systems.

Brought to you by Dr. Ware, Microsoft Office 365 Silver Partner, Charleston SC.