Tuesday, 30 June 2009

Timer function for PostgreSQL

This function will return execution time for any SELECT statement given as a parameter. It is useful for queries in psql.

DROP FUNCTION IF EXISTS timer(VARCHAR);
CREATE FUNCTION timer(VARCHAR)
RETURNS INTERVAL AS'

DECLARE
t1 TIMESTAMP;
t2 TIMESTAMP;

BEGIN

t1 = timeofday();
EXECUTE $1;
t2 = timeofday();

RETURN (t2 - t1);
END;'
language 'plpgsql';


EXAMPLE:
=> SELECT timer('SELECT foo FROM bar LIMIT 100');

-[ RECORD 1 ]----------
timer | 00:00:00.012927

No comments: