psycopg2.pool.SimpleConnectionPool

1201 ワード

公式ドキュメントはこちら
ここでは、通常のconnectionとpoolを使用したconnectionについて、通常のコードを10000回クエリーしてテストしました.
import psycopg2
from time import time

t = time()
n = 10000
while n:
    n -= 1
    conn = psycopg2.connect(dbname = 'enterprise-test', user = 'lovedrose', password = '', host = '127.0.0.1')
    cur = conn.cursor()
    cur.execute('select * from cmps_key_value')
    cur.fetchall()
print(time() - t)
  :52.5323209763

接続プールのコードを使用
import psycopg2.pool
from time import time

t = time()
n = 10000
lst = [str(i) for i in range(20)]
simple_conn_pool = psycopg2.pool.SimpleConnectionPool(5, 200, host = '127.0.0.1',user = 'lovedrose', password = '', dbname = 'enterprise-test')
while n:
    key = lst.pop(0)
    conn = simple_conn_pool.getconn(key)
    cur = conn.cursor()
    cur.execute('select * from cmps_key_value')
    cur.fetchall()
    n -= 1
    lst.append(key)
print(time() - t)
simple_conn_pool.closeall()
  :4.29549717903

12倍近く速くなりました