PostgreSQL-在c函数中使用日期常量
我正在尝试将以下SQL函数重写为c等效函数(尝试使其更快一点): 我想我可以修改现有的PostgreSQL-在c函数中使用日期常量,c,postgresql,postgresql-9.3,C,Postgresql,Postgresql 9.3,我正在尝试将以下SQL函数重写为c等效函数(尝试使其更快一点): 我想我可以修改现有的date+int4操作符并执行如下操作: #include "postgres.h" #include "fmgr.h" #include "utils/date.h" #ifdef PG_MODULE_MAGIC PG_MODULE_MAGIC; #endif PG_FUNCTION_INFO_V1(dwd); Datum dwd(PG_FUNCTION_ARGS) { /* DateADT
date
+int4
操作符并执行如下操作:
#include "postgres.h"
#include "fmgr.h"
#include "utils/date.h"
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
PG_FUNCTION_INFO_V1(dwd);
Datum
dwd(PG_FUNCTION_ARGS)
{
/* DateADT dateVal = PG_GETARG_DATEADT(0); */
DateADT dateVal = PG_GETARG_DATEADT(2006-12-31);
int32 days = PG_GETARG_INT32(0);
PG_RETURN_DATEADT(dateVal + days);
}
如果我编译我的函数并将其转换为,那么
我可以在PostgreSQL中创建dwd
函数:
create or replace function dwd(int) returns date as
'/usr/lib/postgresql/9.3/lib/dwd', 'dwd'
language c
cost 1;
我得到2000-01-01
forselect dwd(0)代码>,但我预期的是2006-12-31
。显然,DateADT dateVal=PG_GETARG_DateADT(2006-12-31)中存在问题代码>
如何在此c函数中定义日期常量 现在它可以工作了。事实证明,DateADT
是自2000-01-01以来的天数(整数)
c功能:
#include "postgres.h"
#include "fmgr.h"
#include "utils/date.h"
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
PG_FUNCTION_INFO_V1(dwd);
Datum
dwd(PG_FUNCTION_ARGS)
{
int32 days = PG_GETARG_INT32(0);
if (days > 0) {
DateADT dateVal = 2556;
PG_RETURN_DATEADT(dateVal + days);
}
else {
PG_RETURN_NULL();
}
}
性能测试:
drop table if exists tmp;
create table tmp as select dat2(gs) from generate_series(1,1000000) gs;
-- Query returned successfully: 1000000 rows affected, 4101 ms execution time.
drop table if exists tmp;
create table tmp as select dwd(gs) from generate_series(1,1000000) gs;
-- Query returned successfully: 1000000 rows affected, 1527 ms execution time.
在我的搜索过程中,我发现这是PostgreSQL中c函数非常有用的参考。是什么让你认为这是查询执行中的热点/慢点?日期/时间数学并不便宜。@CraigRinger我们在查询中经常使用这个函数,我想测试c函数是否会更快。这应该是整个数据仓库的通用功能。目前,我对任何特定的查询都没有问题。可能值得先分析一下,看看它是否对性能有任何有意义的影响。CraigRinger只是想让你知道-c函数dwd
比SQL函数dat2
快三倍,请看我的答案。当然,如果dat2
是(比如说)执行成本的2%,您没有获得多少收益。这就是我所说的:首先,值得分析一下,看看你正在优化的东西是否真的值得改进。
drop table if exists tmp;
create table tmp as select dat2(gs) from generate_series(1,1000000) gs;
-- Query returned successfully: 1000000 rows affected, 4101 ms execution time.
drop table if exists tmp;
create table tmp as select dwd(gs) from generate_series(1,1000000) gs;
-- Query returned successfully: 1000000 rows affected, 1527 ms execution time.