【问题标题】:Postgres: timing the runtime of a functionPostgres:计时函数的运行时间
【发布时间】:2019-11-15 23:35:20
【问题描述】:

我想更新一个存储函数/存储过程持续时间的审计表,

到目前为止我有

drop table if exists tmp_interval_test;
create table tmp_interval_test (
    id serial primary key,
    duration interval
);

drop function if exists tmp_interval;
create or replace function tmp_interval()
    returns void as 

    $body$
    declare
        sleep int;
        start_time timestamp;
        end_time timestamp;
        diff interval;

    begin
        start_time := now();
        sleep := floor(random() * 10 + 1)::int;

        -- actual code goes here
        perform pg_sleep(sleep);
        end_time := now();

        diff := age(end_time, start_time);

        insert into tmp_interval_test (duration) values (diff);
    end;

    $body$
language 'plpgsql' volatile;

但是,当我测试这个功能时,会显示持续时间

id|duration|
--|--------|
 1|00:00:00|

如何正确地将持续时间插入到我的表格中?

【问题讨论】:

    标签: postgresql plpgsql


    【解决方案1】:

    now() 函数返回事务时间 - 在一个事务中是相同的。所以 0 是正确的结果。您应该使用不同的函数来实时返回 - 请改用 clock_timestamp() 函数。

    另一方面,如果你想收集函数的时间,你可以使用 Postgres 中的内置功能(如果有超级用户权限)。激活tracking functions。然后就可以在系统表pg_stat_user_function看到你需要的了。

    【讨论】:

      【解决方案2】:

      见SO regarding now()

      更新函数并使用clock_timestamp()代替now(),例如,

      start_time := clock_timestamp();
      

      【讨论】:

      • current_timestamp 无能为力,它再次返回事务时间 - 并且存在语法错误 - 它是伪常数。 Postgres 函数每次都在事务下运行。
      • 你想要clock_timestamp()
      • 是的,我很抱歉我的意思是把clock_timestamp() 抱歉会解决这个问题
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2021-10-20
      • 1970-01-01
      相关资源
      最近更新 更多