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

如何在Python中获取PostgreSQL游标的执行时间

获取PostgreSQL查询的服务器端执行耗时

首先得明确:psycopg2的cursor对象并没有fetchtime()方法,这就是你代码报错的核心原因。不过有几种可靠的方法能拿到PostgreSQL服务器端的查询执行时间,下面给你详细说明:

方法一:利用PostgreSQL内置的pg_stat_statements扩展

这个扩展能跟踪所有SQL语句的执行统计,包括耗时。不过需要先在数据库中启用它:

  1. 修改postgresql.conf配置文件,添加以下内容:

    shared_preload_libraries = 'pg_stat_statements'
    pg_stat_statements.track = all
    

    保存后重启PostgreSQL服务。

  2. 在目标数据库中创建扩展:

    CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
    
  3. 执行查询后,通过视图获取耗时:

    import psycopg2
    
    conn = psycopg2.connect(host="localhost", database="shrek", user="postgres", password="apple")
    cur = conn.cursor()
    
    # 执行目标查询
    cur.execute('SELECT id FROM company')
    result = cur.fetchone()
    print(result[0])
    
    # 查询当前会话最近一次目标查询的服务器端耗时
    cur.execute("""
        SELECT total_time 
        FROM pg_stat_statements 
        WHERE query = 'SELECT id FROM company' 
          AND pid = pg_backend_pid()
        ORDER BY query_start DESC 
        LIMIT 1;
    """)
    execution_time = cur.fetchone()[0]
    print(f"服务器端查询耗时:{execution_time} 毫秒")
    
    cur.close()
    conn.close()
    

方法二:用PostgreSQL时间函数直接计算

这种方法不需要额外扩展,通过在查询前后记录服务器端时间来计算差值:

import psycopg2

conn = psycopg2.connect(host="localhost", database="shrek", user="postgres", password="apple")
cur = conn.cursor()

# 记录服务器端开始时间
cur.execute("SELECT clock_timestamp() AS start_time")
start_time = cur.fetchone()[0]

# 执行实际查询
cur.execute('SELECT id FROM company')
result = cur.fetchone()
print(result[0])

# 记录服务器端结束时间并计算耗时
cur.execute("SELECT clock_timestamp() AS end_time")
end_time = cur.fetchone()[0]
execution_duration = (end_time - start_time).total_seconds() * 1000  # 转换为毫秒
print(f"服务器端查询耗时:{execution_duration:.2f} 毫秒")

cur.close()
conn.close()

方法三:使用EXPLAIN ANALYZE(适合测试场景)

如果只是想测试查询的执行耗时,不需要获取实际查询结果,可以用EXPLAIN ANALYZE,它会返回详细执行计划和实际耗时:

import psycopg2

conn = psycopg2.connect(host="localhost", database="shrek", user="postgres", password="apple")
cur = conn.cursor()

cur.execute("EXPLAIN ANALYZE SELECT id FROM company")
# 遍历输出结果,找到执行耗时行
for line in cur.fetchall():
    print(line[0])

cur.close()
conn.close()

输出内容里会包含类似Execution Time: 0.123 ms的行,这就是服务器端的执行耗时。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 14:57:29