Created
March 12, 2016 16:17
-
-
Save areski/7de6c0fb770ae331ee3b to your computer and use it in GitHub Desktop.
PLPGSQL example - accumulator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- | |
-- Benchmark PLPGSQL | |
-- | |
DROP TABLE accumulator; | |
CREATE TABLE accumulator (id BIGSERIAL PRIMARY KEY, new_value INT, sum_previous INT); | |
CREATE OR REPLACE FUNCTION "fillaccumulator"() RETURNS boolean AS | |
$BODY$ | |
DECLARE | |
acc_count integer; | |
acc_sum integer; | |
randint integer; | |
BEGIN | |
SELECT count(*), SUM(new_value) INTO acc_count, acc_sum FROM "accumulator"; | |
IF FOUND THEN | |
randint = trunc(random() * 99 + 1); | |
INSERT INTO "accumulator" ("new_value", "sum_previous") VALUES (randint, acc_sum); | |
RETURN TRUE; | |
END IF; | |
RETURN FALSE; | |
END; | |
$BODY$ LANGUAGE plpgsql; | |
CREATE OR REPLACE FUNCTION plbench(query text, n int) returns float as $$ | |
DECLARE | |
t0 timestamp with time zone; | |
e float; | |
BEGIN | |
t0 := clock_timestamp(); | |
for i in 1 .. n loop | |
execute query; | |
end loop; | |
e = extract(microseconds from clock_timestamp()) - extract(microseconds from t0); | |
return e / 1000000; | |
END; | |
$$ language plpgsql; | |
SELECT plbench('SELECT fillaccumulator()', 10000); | |
-- SELECT count(*), SUM(new_value) FROM accumulator; | |
SELECT * FROM accumulator ORDER BY id DESC LIMIT 1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment