Create function:
CREATE OR REPLACE FUNCTION pid_mem_usage( pid integer)
RETURNS integer AS $$
DECLARE l_command TEXT; res integer;
BEGIN
SET client_min_messages = 'error';
l_command := ' cat /proc/' || pid || '/smaps | grep "^Private" | awk ''{a+=$2}END{print a * 1024}'' ';
raise notice '%',l_command;
execute 'create temp table if not exists z (a int) ';
execute 'copy z from program ' || quote_literal(l_command);
execute 'select sum(a) from z' into res;
execute 'truncate z';
RETURN res;
END;
$$ LANGUAGE plpgsql;
Sample usage:
select pid_mem_usage(pid),pid,usename,backend_start,xact_start,
query from pg_stat_activity order by 1 desc limit 25;
Based on from https://www.depesz.com/2012/06/09/how-much-ram-is-postgresql-using/