我想加快以下(PostgreSQL)代码的速度,我推测它会有助于摆脱(一些)循环,但我看不到这样做的方法。欢迎任何关于加速的建议。提前致谢!
该代码为不同部分的每列计算一些统计数据(平均值、斜率)。该部分由滑动时间窗口(例如 60 分钟)确定。所以下面的代码
- 循环遍历我对计算其统计数据感兴趣的不同列
对于每一列,我依次移动我的时间窗口并计算该窗口中值的统计信息。
for col_name in ..... a list of column names truncate small_table; -- where statistics are temporarily stored for cur in select time from big_table loop execute 'select regr_slope('|| col_name ||', time) as slope,' || ' avg(' || col_name || ') as mean' || ' from big_table where' || ' time <=' || cur.time || ' and time >=' || cur.time-60 into result; execute 'insert into small_table values($1,$2,$3)' using cur.time, result.slope, result.mean; end loop; execute 'update big_table set ' || col_name || '_slope = small_table.slope, ' || col_name || '_mean = small_table.mean ' || ' where big_table.time=small_table.time'; end loop;
small_table
,结果被临时存储,被引入以避免多次更新big_table
.
small_table
并big_table
具有相同的结构,但小表的行数要少得多。两个表的列是
time | field_1 | field_2 | field_1_slope | field_1_mean | field_2_slope | field_2_mean
实际上有很多列(〜50),这可能是另一个放缓的因素?