Get execution time of PostgreSQL query

前端 未结 3 1284
一生所求
一生所求 2020-12-23 13:28
DECLARE @StartTime datetime,@EndTime datetime

SELECT @StartTime=GETDATE()

select distinct born_on.name
from   born_on,died_on
where (FLOOR((\'2012-01-30\'-born_on.         


        
3条回答
  •  醉酒成梦
    2020-12-23 13:49

    PostgreSQL is not Transact-SQL. These are two slightly different things.

    In PostgreSQL, this would be something along the lines of

    DO $proc$
    DECLARE
      StartTime timestamptz;
      EndTime timestamptz;
      Delta double precision;
    BEGIN
      StartTime := clock_timestamp();
      PERFORM foo FROM bar; /* Put your query here, replacing SELECT with PERFORM */
      EndTime := clock_timestamp();
      Delta := 1000 * ( extract(epoch from EndTime) - extract(epoch from StartTime) );
      RAISE NOTICE 'Duration in millisecs=%', Delta;
    END;
    $proc$;
    

    On the other hand, measuring query time does not have to be this complicated. There are better ways:

    1. In postgres command line client there is a \timing feature which measures query time on client side (similar to duration in bottomright corner of SQL Server Management Studio).

    2. It's possible to record query duration in server log (for every query, or only when it lasted longer than X milliseconds).

    3. It's possible to collect server-side timing for any single statement using the EXPLAIN command:

      EXPLAIN (ANALYZE, BUFFERS) YOUR QUERY HERE;
      

提交回复
热议问题