CREATE or replace FUNCTION create_seq(n integer) RETURNS void
    LANGUAGE plpgsql
    AS $$
BEGIN
    drop table if exists testseqs;
    create table testseqs(seqoid oid, n int4);
    WHILE n > 0 LOOP
        EXECUTE 'CREATE SEQUENCE testseq' || n;
	insert into testseqs select oid, n from pg_class where relname=('testseq' || n);
      n := n - 1;
    END LOOP;
END
$$;

CREATE or replace FUNCTION drop_seq() RETURNS void language plpgsql as
$$
declare
   n int4;
begin
   for n in select testseqs.n from testseqs loop
     execute 'drop sequence testseq' || n;
   end loop;
end;
$$;


CREATE or replace FUNCTION nextval_seq(nseqs integer, niter integer) RETURNS bigint
    LANGUAGE sql
    AS $$
select count(*) from (
  select nextval(seqoid), n, g from testseqs, generate_series(1, niter) g where n <= nseqs
) foo;
$$;


CREATE or replace FUNCTION currval_seq(nseqs integer, niter integer) RETURNS bigint
    LANGUAGE sql
    AS $$
select count(*) from (
  select currval(seqoid), n, g from testseqs, generate_series(1, niter) g where n <= nseqs
) foo;
$$;


\timing on
--select create_seq(10000);

\echo warmup
select nextval_seq(10000, 100);

\echo calling nextval on 10000 distinct sequences, 100 times
select nextval_seq(10000, 100);

\echo calling currval on 1 sequence, 1000000 times
select currval_seq(1, 1000000);

\echo calling currval on 2 sequences, 500000 times
select currval_seq(2, 500000);

\echo calling currval on 4 sequences, 250000 times
select currval_seq(4, 250000);

\echo calling currval on 5 sequences, 200000 times
select currval_seq(5, 200000);

\echo calling currval on 10 sequences, 100000 times
select currval_seq(10, 100000);

\echo calling currval on 100 sequences, 10000 times
select currval_seq(100, 10000);

\echo calling currval on 1000 sequences, 1000 times
select currval_seq(1000, 1000);

\echo calling currval on 10000 distinct sequences, 100 times
select currval_seq(10000, 100);


