You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

psycopg2连接TimescaleDB时查询性能远低于IDE控制台的原因排查

问题:psycopg2与PyCharm控制台查询TimescaleDB性能差异原因

我使用psycopg2连接本地Docker容器中的TimescaleDB实例,需要从包含3500万行数据的prices表中查询各资产的最新价格。

表结构

create table prices
(
    datetime   timestamptz not null,
    asset_id   integer references assets (asset_id),
    price      real        not null,
    created_at timestamptz not null default now(),

    unique (datetime, asset_id)
);

超表转换

已通过以下语句将该表转换为TimescaleDB超表:

select create_hypertable('"prices"', 'datetime');

索引创建

参考官方文档创建了索引:

create index latest_prices_idx on prices (asset_id, datetime desc);

查询语句

使用官方推荐的"Option 3"查询各资产最新价格:

select distinct on (asset_id) datetime, asset_id, price
from prices
order by asset_id, datetime desc;

性能差异现象

  • 该查询在PyCharm控制台执行仅需约300ms;
  • 通过psycopg2执行却耗时约10秒,代码如下:
cursor.execute("""
    select distinct on (asset_id) datetime, asset_id, price
    from prices
    order by asset_id, datetime desc;
""")
res = cursor.fetchall()
  • 两者的EXPLAIN结果完全一致。

补充信息

  • 数据库运行在本地Docker容器中;
  • 使用服务器端游标无性能改善;
  • 在容器内通过psql执行该查询同样耗时约10秒;
  • 删除索引后性能反转:psycopg2与psql耗时约6秒,PyCharm控制台耗时约13秒;重建索引后恢复原性能差异。

请问造成这种性能差异的原因是什么?


内容的提问来源于stack exchange,提问作者trivicious

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 11:22:14