pg_stat_user_functions Call Timing

Read pg_stat_user_functions to see how often each PL/pgSQL function runs and how much time it consumes, gated by track_functions.

SqlData Fetching

Code

snippet
-- 函数级统计默认关闭:track_functions 控制开关(pl 只统计 PL/pgSQL)
SHOW track_functions;   -- 默认 none;改 pl/all 后需要新会话才生效

CREATE FUNCTION add_tax(cents int) RETURNS int LANGUAGE plpgsql AS $$
BEGIN
    RETURN cents + cents * 20 / 100;
END $$;

CREATE FUNCTION trim_note(t text) RETURNS text LANGUAGE sql
RETURNS NULL ON NULL INPUT AS $$ SELECT btrim(t) $$;

-- 调用后统计会累积:calls 次数、total_time/self_time 微秒
SELECT add_tax(100), trim_note('  hi  ');

-- self_time 排除被调用子函数的耗时;行级触发器不计入函数统计
SELECT schemaname, funcname, calls, total_time, self_time
FROM pg_stat_user_functions
WHERE schemaname = 'public'
ORDER BY total_time DESC;

How it works

What runs here is SELECT / CREATE — pg_stat_user_functions are the objects involved.

Mechanically, the statements are built from: a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order.

Applying it

Point it at the pg_stat_user_functions table.

Statements that matter

SELECT schemaname, funcname, calls, total_time, self_time
FROM pg_stat_user_functions
WHERE schemaname = 'public'
ORDER BY total_time DESC;
CREATE FUNCTION trim_note(t text) RETURNS text LANGUAGE sql
RETURNS NULL ON NULL INPUT AS $$ SELECT btrim(t) $$;
CREATE FUNCTION add_tax(cents int) RETURNS int LANGUAGE plpgsql AS $$
BEGIN
    RETURN cents + cents * 20 / 100;
END $$;

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
`pg_stat_user_functions`.