如何在Python中获取PostgreSQL游标的执行时间
获取PostgreSQL查询的服务器端执行耗时
首先得明确:psycopg2的cursor对象并没有fetchtime()方法,这就是你代码报错的核心原因。不过有几种可靠的方法能拿到PostgreSQL服务器端的查询执行时间,下面给你详细说明:
方法一:利用PostgreSQL内置的pg_stat_statements扩展
这个扩展能跟踪所有SQL语句的执行统计,包括耗时。不过需要先在数据库中启用它:
修改
postgresql.conf配置文件,添加以下内容:shared_preload_libraries = 'pg_stat_statements' pg_stat_statements.track = all保存后重启PostgreSQL服务。
在目标数据库中创建扩展:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;执行查询后,通过视图获取耗时:
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
相关产品推荐
相关产品推荐

