V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
ballshapesdsd
V2EX  ›  问与答

psycopg2 的损耗怎么这么大?

  •  
  •   ballshapesdsd · 2017-07-06 15:23:27 +08:00 · 1537 次点击
    这是一个创建于 2484 天前的主题,其中的信息可能已经有所发展或是发生改变。
    用的 postgresql 数据库,在 python 下用的 psycopg2 连接数据库。

    select 一个大概 500 万行的表,加了索引。
    在 python 下循环 10000 次,用 psycopg2 select,用了 6.20757 s。
    在数据库里编写函数,直接 select 10000 次,只需要 0.074269 s。

    这时间也差的太多了吧,直接差 100 倍的速度?

    后来在 python 下循环 10000 次,直接 select 1 ;,用了 3.55476 s。平均一次就有 0.0003s。
    这种空 select 居然有这么大损耗,简直忍不了啊。难道传输 sql 命令的损耗有这么大?有什么办法提高速度吗?
    3 条回复    2017-07-07 14:45:04 +08:00
    leeoo
        1
    leeoo  
       2017-07-07 14:22:14 +08:00
    题主把测试代码贴出来看下。或者试试用 pg8000 对比下性能怎么样。
    ballshapesdsd
        2
    ballshapesdsd  
    OP
       2017-07-07 14:44:02 +08:00
    @leeoo

    @profile
    def aaa():
    for i in range(10000):
    sqlcmd='''select * from link_tbl where link_id=10360000000013'''
    cur.execute(sqlcmd)
    b=cur.fetchall()
    aaa()

    @profile
    def bbb():
    sqlcmd='''
    CREATE OR REPLACE FUNCTION bbb()
    RETURNS smallint
    LANGUAGE plpgsql volatile
    AS $$
    DECLARE
    node_id bigint;
    i integer;
    BEGIN
    for i in 1..10000 loop
    select s_node into node_id from link_tbl where link_id=10360000000013;
    end loop;
    return 1;
    END;
    $$;
    select bbb();
    '''
    cur.execute(sqlcmd)
    conn_str.commit()

    bbb()

    @profile
    def ccc():
    for i in range(10000):
    sqlcmd='''select 10360000000013;'''
    cur.execute(sqlcmd)
    b=cur.fetchall()

    ccc()
    ballshapesdsd
        3
    ballshapesdsd  
    OP
       2017-07-07 14:45:04 +08:00
    现在问题解决了,我把整个数据表加载到内存里,用字典存起来,这样查询快很多,不过内存用了 7,8 个 g。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5446 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 07:06 · PVG 15:06 · LAX 00:06 · JFK 03:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.