7

I need, in a plpgsql script, to get the execution time of the last query in a variable for several purposes (calculation, display and storage), so the psql \timing option is not what I look for because I can't manipulate the result time. Do you know if there is anything like the "get diagnostics" command, but for execution time (or work around) ?:

get diagnostics my_var := EXECUTION_TIME;

I couldn't find anything else than row_count and result_oid...

1 Answer 1

28

You can compare clock_timestamp() before and after the query:

do $$
declare t timestamptz := clock_timestamp();
begin
 perform pg_sleep(random());
 raise notice 'time spent=%', clock_timestamp() - t;
end
$$ language plpgsql;

Sample result:

NOTICE: time spent=00:00:00.59173

Sign up to request clarification or add additional context in comments.

1 Comment

Actually I tried this but with now(), since it is the transaction time, I had the same time before and after, but with clock_timestamp() it works ! thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.