Track Function Execution Stats with pg_stat_user_functions
Track Function Execution Stats with pg_stat_user_functions
pg_stat_user_functions holds one row for each tracked function. Each row shows how many times the function ran, the total time spent in it, and the time spent in its own body. On a default install the view is empty, because track_functions starts at none. The script below joins the view to pg_proc and returns the 300 functions with the highest total_time, each with a quoted full name and its oid.
Purpose and Overview
Where pg_stat_statements aggregates per statement, pg_stat_user_functions aggregates per function. Say a PL/pgSQL routine calls three PL/pgSQL helpers. With tracking on, the view shows four rows, each with its own call count and timings. That split shows you which function in the chain spends the time.
PostgreSQL counts calls to user-defined functions, and the time spent in each, only when tracking is enabled. Statistics collection adds some overhead to query execution, so the server lets you choose what it collects. Function tracking is off by default. track_counts is the opposite case: it is on by default because the autovacuum daemon needs the data it collects.
The script returns tag_schema, tag_function_name, tag_function_full_name (schema and name, quoted), tag_oid, sp_calls, self_time and total_time, plus an epoch_ns timestamp. Both time columns are in milliseconds. The tag_ and sp_ prefixes are naming for a metrics collector that stores each row as a tagged data point. They don't change what the query reads.
Sample Code
1select /* pgwatch2_generated */
2 (extract(epoch from now()) * 1e9)::int8 as epoch_ns,
3 schemaname::text AS tag_schema,
4 funcname::text AS tag_function_name,
5 quote_ident(schemaname)||'.'||quote_ident(funcname) as tag_function_full_name,
6 p.oid::text as tag_oid, -- for overloaded funcs
7 calls as sp_calls,
8 self_time,
9 total_time
10FROM
11 pg_stat_user_functions f
12 JOIN
13 pg_proc p ON p.oid = f.funcid
14ORDER BY
15 total_time DESC
16LIMIT
17 300;
18
19-- BSD 3-Clause License
20--
21-- Copyright (c) 2016-2023, CYBERTEC PostgreSQL International GmbH
22-- All rights reserved.
23--
24-- Redistribution and use in source and binary forms, with or without
25-- modification, are permitted provided that the following conditions are met:
26--
27-- * Redistributions of source code must retain the above copyright notice, this
28-- list of conditions and the following disclaimer.
29--
30-- * Redistributions in binary form must reproduce the above copyright notice,
31-- this list of conditions and the following disclaimer in the documentation
32-- and/or other materials provided with the distribution.
33--
34-- * Neither the name of the copyright holder nor the names of its
35-- contributors may be used to endorse or promote products derived from
36-- this software without specific prior written permission.
37--
38-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
39-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
40-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
41-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
42-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
43-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
44-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
45-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
47-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Notes: This needs PostgreSQL 8.4 or later, the release that added pg_stat_user_functions. Set track_functions to pl or all before you run it, or it returns no rows. Change LIMIT 300 to suit the database. Drop the epoch_ns column if you read the output by hand instead of storing it in a time-series system. If you redistribute the script, keep the copyright notice, the list of conditions and the disclaimer at the end of the block, because the BSD 3-Clause licence requires all three.
Code Breakdown
The query is a single join with a sort, and it returns rows only when track_functions is on.
Enabling track_functions
track_functions takes three values. pl tracks procedural-language functions only. all also tracks SQL and C language functions. none, the default, turns function tracking off. Only superusers and roles with the SET privilege on the parameter can change it.
Even with all, PostgreSQL never tracks a SQL function that the planner inlines into the calling query. So if a short SQL helper is missing from the output, that does not prove it never ran. It may have been folded into the query that called it. Under pl, SQL functions are left out entirely.
Joining pg_proc on funcid
pg_proc stores functions, procedures, aggregate functions and window functions. Its oid column is the row identifier, and the join matches it to the view's funcid. As a result, tag_oid carries the same value as funcid. The join also lets you add any other pg_proc column to the output when you need more detail about a function.
Overloaded functions share a funcname, so two versions of public.x with different argument lists show up as two rows with the same name. Only the oid tells them apart. The inline comment -- for overloaded funcs marks this.
Quoting the full name
quote_ident quotes the schema and the function name separately, and then the two are joined with a dot. Because each part is quoted on its own, the schema-qualified name stays valid when either part needs quotes, so you can paste tag_function_full_name into a follow-up query.
Sorting by total_time
total_time is the time spent in the function and in every function it calls. A top-level entry point therefore sorts at or near the top even if its own body does almost nothing. To rank functions by the work done inside their own code, change the ORDER BY to self_time DESC.
Key Function Statistics Concepts
self_time vs total_time
self_time is the time spent in the function itself, not counting the functions it calls. A thin wrapper shows a large total_time and a self_time near zero. In one worked example from the 8.4 development cycle, two overloads of a function x ran about 1,000 times each. One had total_time and self_time both at 502679. The other had a total_time of 499513 and a self_time of 56. The first did its own work. The second passed nearly all of it to something it called.
Counter lag and transaction caching
The numbers are not live to the millisecond. Each backend sends its counters to shared statistics no more than once every PGSTAT_MIN_INTERVAL milliseconds, which is 1 second unless someone changed it when building the server. A call that finished a moment ago can be missing from the view.
Reads are cached too. Under the default stats_fetch_consistency = cache, values you read stay cached until the end of the current transaction. If you query the view twice inside one transaction, you get the same numbers both times. With stats_fetch_consistency = none, each access fetches the counters from shared memory again. That makes none the setting suited to monitoring systems.
pg_stat_xact_user_functions
pg_stat_xact_user_functions has the same shape but counts only the calls made during the current transaction. Those calls are not yet in pg_stat_user_functions. Use it inside a test transaction to see the cost of one code path without waiting for the counters to flush.
When counters reset
Cumulative statistics live in shared memory. After a server crash, a start from a base backup, or point-in-time recovery, every counter is reset. A drop in sp_calls on a monitoring graph can therefore be a reset, not a fall in traffic. In PostgreSQL 19 the view's stats_reset column shows when the counters were last reset.
Practical Applications
The output is a ranked list of where the server spends time inside your own code.
Find the PL/pgSQL hot spot behind a slow endpoint
Sort by self_time and look at the top five rows. A function with a high self_time spends the time in its own body: its loops, its queries, its row-by-row logic. Rewrite that function first. Divide self_time by sp_calls to tell a function that is slow on each call from one that is cheap but called too often.
Separate wrappers from workers
Where total_time is high and self_time is close to zero, the row is a wrapper. Tuning its body gains nothing. Follow its calls down to the functions where self_time is close to total_time, and work on those.
Measure a function rewrite
Before you deploy a new version, run pg_stat_reset_single_function_counters(oid) with the oid from tag_oid. That resets the counters for that one function in the current database. Then compare the per-call time after a day of traffic. The function is restricted to superusers by default, and you can grant EXECUTE on it to other roles. Avoid pg_stat_reset() for this job. It resets every counter in the current database, including the counters autovacuum uses to decide when to vacuum or analyze.
Feed a monitoring system
The epoch_ns column gives each row a nanosecond timestamp, and the tag_ columns become labels in the metrics store. Set stats_fetch_consistency = none for the collector's session, so each scrape re-reads the counters from shared memory instead of caching values it reads only once. The counters themselves still lag by up to the flush interval. Because the counters are cumulative, graph the difference between scrapes rather than the raw values.
Version Compatibility
PostgreSQL 8.4 added the view, together with the track_functions parameter that controls it. The columns the script reads (funcid, schemaname, funcname, calls, total_time, self_time) were already in the 8.4 version of the view.
PostgreSQL 15 moved cumulative statistics into shared memory and removed the separate statistics collector process. The query is the same before and after that change. What changed is where the counters live and how backends report them.
PostgreSQL 19 adds a stats_reset column to pg_stat_user_functions. In PostgreSQL 18 the view ends at self_time. The script does not select stats_reset, so it runs unchanged on 8.4 through 19. To show the last reset time on 19, add f.stats_reset to the select list. Leave it out on 18 and earlier.
Best Practices
- Start with
pl, move toallwith a reason — tracking adds overhead, andplcovers PL/pgSQL functions. - Grant EXECUTE instead of superuser — give the reset function to the role that runs performance tests, and nothing more.
- Reset one function, never the database —
pg_stat_reset()also clears the autovacuum counters. - Export the oid — overloads share a name, and a dashboard keyed on
funcnamealone merges them into one line.
References
- PostgreSQL Docs: The Cumulative Statistics System — view columns, counter flush interval, transaction caching,
pg_stat_xact_user_functions, reset functions and when counters reset - PostgreSQL Docs: Run-time Statistics —
track_functionsvalues and privilege, inlined SQL functions,stats_fetch_consistency,track_countsdefault - PostgreSQL 18 Docs: The Cumulative Statistics System — the PostgreSQL 18 view without
stats_reset - PostgreSQL 8.4 Release Notes —
pg_stat_user_functionsandtrack_functionsintroduced - PostgreSQL 15 Release Notes — statistics moved to shared memory, collector process removed
- PostgreSQL Docs: pg_proc — what
pg_procstores,oidandproname - Waiting for 8.4 – function stats — overloaded functions sharing a name, the
self_timevstotal_timeexample - pgwatch2 sproc_stats metric.sql — the script (BSD 3-Clause, LICENSE)
Posts in this series
- Identify Underutilized PostgreSQL Columns for Optimization
- Find Unused PostgreSQL Indexes with pg_stat_all_indexes
- Monitor PostgreSQL HOT Updates and Fillfactor
- Find PostgreSQL Index Bloat and Wasted Space
- Estimate PostgreSQL Table Bloat with SQL
- Find Missing Indexes in PostgreSQL with SQL
- Monitor PostgreSQL Table Cache Hit Ratio with SQL
- Tune PostgreSQL Background Writer with pg_stat_bgwriter
- Query PostgreSQL I/O Statistics with pg_stat_io
- Summarize the Buffer Cache with pg_buffercache_summary
- Monitor Logical Replication Slot Stats with pg_stat_replication_slots
- Track Function Execution Stats with pg_stat_user_functions