Skip to content

Instantly share code, notes, and snippets.

@chochkov
Last active December 27, 2015 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chochkov/7284325 to your computer and use it in GitHub Desktop.
Save chochkov/7284325 to your computer and use it in GitHub Desktop.
Compare PL/R implementation of an average to PostgreSQL `avg()`
CREATE OR REPLACE FUNCTION r_mean(float8) RETURNS FLOAT AS $$
return(mean(arg1))
$$ language 'plr';
CREATE AGGREGATE mean (
sfunc = plr_array_accum,
basetype = float8,
stype = _float8,
finalfunc = r_mean
);
CREATE UNLOGGED TABLE things (floats float8);
INSERT INTO things SELECT generate_series(1, 1e5::int);
SELECT avg(floats) from things;
-- 30 ms
SELECT mean(floats) from things;
-- 7 sec, and grows exponentially with number of rows !
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment