额外时间未反映在 PostgreSQL EXPLAIN ANALYZE 中?

Extra Time not reflected in PostgreSQL EXPLAIN ANALYZE?

在 PostgreSQL 中打开 \timing,我可以看到向 ​​运行 发送命令所花费的时间。

我 运行 在两台机器上使用相同的数据库和索引进行相同的查询,但我看到的结果截然不同。

在第一台机器上:

machine1=# EXPLAIN ANALYZE INSERT INTO "notes" ("content", "date", "inserted_at", "updated_at", "user_id") VALUES ('Something of note', '2015-4-27', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 1) RETURNING id;
                                     QUERY PLAN
---------------------------------------------------------------------------------------------
Insert on notes  (cost=0.00..0.03 rows=1 width=0) (actual time=0.055..0.055 rows=1 loops=1)
  ->  Result  (cost=0.00..0.03 rows=1 width=0) (actual time=0.016..0.016 rows=1 loops=1)
  Planning time: 0.048 ms
  Trigger for constraint notes_user_id_fkey: time=0.177 calls=1
  Execution time: 0.286 ms
(5 rows)

Time: 2.218 ms

在第二台机器上:

machine2=> EXPLAIN ANALYZE INSERT INTO "notes" ("content", "date", "inserted_at", "updated_at", "user_id") VALUES ('Something of note', '2015-4-27', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 1) RETURNING id;
                                     QUERY PLAN
---------------------------------------------------------------------------------------------
Insert on notes  (cost=0.00..0.01 rows=1 width=0) (actual time=0.049..0.049 rows=1 loops=1)
  ->  Result  (cost=0.00..0.01 rows=1 width=0) (actual time=0.015..0.015 rows=1 loops=1)
  Planning time: 0.040 ms
  Trigger for constraint notes_user_id_fkey: time=0.118 calls=1
  Execution time: 0.196 ms
(5 rows)

Time: 86.452 ms

两个问题:

1)为什么比计划+执行时间多?

2) 额外的时间包括什么,这会在这些机器之间产生如此大的差异?

EXPLAIN ANALYZE 是一个 服务器端 命令。它报告 服务器端 执行时间。如果您只需要 运行 时间,您可以选择将其 运行 设为 EXPLAIN (ANALYZE, TIMING OFF),因为在 ANALYZE 模式下默认启用的计时开销将使查询花费更长的时间比没有 EXPLAIN ANALYZE.

psql 是客户端应用程序。它的 \timing 命令报告 客户端 运行 从发送查询到接收和处理结果的时间。重要的是,psql 的 \timing 结果受 client/server 往返时间 的影响,而 EXPLAIN ANALYZE 则不受此影响。

还有 log_min_duration_statement,它告诉 PostgreSQL 在不进行分析的情况下记录服务器端查询持续时间,同时仍将结果返回给客户端。您可以要求 PostgreSQL 使用 SET client_min_messages = 'log'; 将此信息发送到客户端 - 然而, 只有超级用户可以设置 log_min_duration_statement 因为它会影响日志记录和客户端报告,使得它的用处不大。如果客户端可以要求 PostgreSQL 发送服务器端计时信息以及查询结果而不需要超级用户,那就太好了。

从您的示例输出来看,您似乎正在使用单个客户端连接到两台不同的计算机。结果集数据大小大致相同。所以我想说的区别很可能是往返时间。 Ping 每个主机。