PostgreSQL ships an extension that does exactly this. It normalizes each statement into a shape, keeps running totals per shape in shared memory, and lets you query them like a table. It has to be loaded at server start, so this is a restart the first time.
# postgresql.conf (needs a restart)
shared_preload_libraries = 'pg_stat_statements'
track_io_timing = on # adds read and write time per query; check your platform with pg_test_timing first
-- then, once, in the database you care about
CREATE EXTENSION pg_stat_statements;
Now ask the question from the top of the page: which shapes use the most total time?
SELECT left(query, 60) AS query,
calls,
round(total_exec_time) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
round(100 * total_exec_time / sum(total_exec_time) OVER (), 1) AS pct,
shared_blks_read AS disk_blocks
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;Read the pct column first. On most systems a handful of shapes add up to most of the time. That is your list. The disk_blocks column tells you which ones are reading from disk instead of from shared buffers.
The numbers are totals since the last reset. To see what changed this week, save a snapshot, call pg_stat_statements_reset(), and compare next week. Or diff two snapshots without resetting.
You also want the plan of the slow runs, not just the totals. auto_explain writes the plan of any statement slower than a threshold into the server log:
# postgresql.conf
session_preload_libraries = 'auto_explain'
auto_explain.log_min_duration = '500ms'
auto_explain.log_analyze = off # on means every statement is timed, which costs CPU on a busy server
log_min_duration_statement = '1s' # a plain catch-all for the really slow ones
log_lock_waits = on # logs waits longer than deadlock_timeout
SHOW log_min_duration_statement;
SHOW shared_preload_libraries;