问题
I noticed that the connection to PostgreSQL is pretty slow.
import psycopg2
import time
start_time = time.time()
try:
db = psycopg2.connect("dbname='xx' user='xxx' host='127.0.0.1' password='xxx' port='5433'")
except Exception as e:
print(e)
exit(1)
print('connect time', time.time() - start_time)
Usual connect time is 2.5-3.5 seconds. connect time 3.3095390796661377
Its pretty much default configuration of freshly installed PostgreSQL. I turned off log_hostname but it changed nothing. I have run both PostgreSQL 9.4 and 10 and both have the same problem. I'm using this machine for development, but even so, I noticed it because my Django requests take 2.5-3.5 seconds which make it unbearable even for development.
Windows 10 Python 2/3 psycopg2 2.7.4
Here relevant logs with max debug from PostgreSQL
2018-03-19 21:24:43.654 +03 [10048] DEBUG: 00000: forked new backend, pid=21268 socket=5072
2018-03-19 21:24:43.654 +03 [10048] LOCATION: BackendStartup, postmaster.c:4099
2018-03-19 21:24:45.248 +03 [21268] LOG: 00000: connection received: host=127.0.0.1 port=9897
It fork new backend and then only 2 seconds later logs connection received
UPD
Even if I manage to avoid connection delay of PostgreSQL ( for example via pgbouncer, or if PostgreSQL running in docker) request still take 1.3-2seconds, but from first sent package till last its only 0.022 second, all other time idk what is happening but not a network communication between client and server. Same code if run within docker - 0.025 second. From windows - 1.3-2sec but network interaction only 0.022sec
There actually two problems that might be caused by same thing or different, no idea.
1) Postgresql not sending the packet for 1.8 seconds for an unknown reason
2) Even if the first problem eliminated and network interaction down to 0.022 sec whole thing still take 1.3-2 sec ( using either psql or psycopg2)
来源:https://stackoverflow.com/questions/49353881/postegresql-slow-connect-time-on-windows