Question

I am using Postgresql. I want to test how much time a function takes to execute. Since the function takes only a few milliseconds, I would like to call it in a loop 1000s of times to get an accurate figure.

MySQL has a BENCHMARK() function to do this. Is there an equivalent or do I have to write a procedure with a loop to do this?

Était-ce utile?

La solution

In PostgreSQL you typically do this with generate_series:

SELECT my_function()
FROM generate_series(1,5000);

or

SELECT (SELECT my_query ....)
FROM generate_series(1,5000);

In the latter case you can add OFFSET 0 to the subquery or wrap it in a STRICT SQL function to prevent the query planner from pulling out common conditions and subclauses and otherwise being clever.

Timing can be obtained with psql's \timing command, with SET log_duration = on, or with EXPLAIN (ANALYZE, BUFFERS), all of which time subtly different things - see the documentation. In brief, \timing measures time including round-trips and value transfer to the client. log_duration measures server-side execution time. EXPLAIN (ANALYZE, BUFFERS) measures details of the statement's execution but adds timing overhead that can slow it down a bit.

Autres conseils

Write a procedure with a loop - shouldn't take more than 5 minutes.

CREATE OR REPLACE FUNCTION benchmark(loop_count int,
                                     sql_expr text, -- SQL expression
                                     is_cache_plan boolean default true) returns interval
    immutable
    strict
    parallel safe -- Postgres 10 or later
    language plpgsql
AS
$$
BEGIN

    if is_cache_plan then
        EXECUTE 'select ($1) from generate_series(1, $2)' using sql_expr, loop_count;
    else
        FOR i IN 1..loop_count LOOP
            EXECUTE 'select ($1)' using sql_expr;
        END LOOP;
    end if;

    RETURN clock_timestamp() - now();
END
$$;

-- TESTS (parse URL)

select benchmark(
    500000,
    $$substring(format('https://www.domain%s.com/?aaa=1111&b[2]=3#test', (random()*1000)::int::text) from '^[^:]+://([^/]+)')$$,
    true);
-- 0 years 0 mons 0 days 0 hours 0 mins 0.300638 secs

select benchmark(
    500000,
    $$substring(format('https://www.domain%s.com/?aaa=1111&b[2]=3#test', (random()*1000)::int::text) from '^[^:]+://([^/]+)')$$,
    false);
-- 0 years 0 mons 0 days 0 hours 0 mins 6.735336 secs

-- TESTS (generate UUID)

SELECT benchmark(1000000, $$uuid_in(overlay(overlay(md5(random()::text || ':' || clock_timestamp()::text) placing '4' from 13) placing to_hex(floor(random()*(11-8+1) + 8)::int)::text from 17)::cstring)$$);
-- 0 years 0 mons 0 days 0 hours 0 mins 0.644648 secs

SELECT benchmark(1000000, $$md5(random()::text || clock_timestamp()::text)::uuid$$);
-- 0 years 0 mons 0 days 0 hours 0 mins 0.449026 secs

SELECT benchmark(1000000, $$gen_random_uuid()$$);
-- 0 years 0 mons 0 days 0 hours 0 mins 0.438084 secs
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top