python - 为什么 psycopg2 对我这么慢?

标签 python postgresql profiling psycopg2 cprofile

我有一个使用 psycopg2 与 postgres 一起工作的程序。 但是插入数据库需要很长时间。

这是使用 cProfile 进行分析的结果。

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
475    0.022    0.000  855.605    1.801 /home/user/my_project/db.py:197(insert_event)
475    0.012    0.000  293.347    0.618 /home/user/my_project/db.py:123(insert_meta)
475    0.026    0.000  276.814    0.583 /home/user/my_project/db.py:102(insert_image)
2375 0.022 0.000 598.542 0.252 /usr/local/lib/python2.7/dist-packages/psycopg2/extras.py:286(execute)
1425  251.676    0.177  251.676    0.177 {method 'commit' of 'psycopg2._psycopg.connection' objects}
475    0.005    0.000   33.028    0.070 /home/user/my_project/db.py:83(is_event)

结论:

Insert full information about one event - 1.8 sec
Insert a picture (average) - 0.583 sec
Insert meta data about an event (average) - 0.618 sec
Confirmation of transaction (average) - 0.177 sec
Check availability of a record in DB - 0.070 sec

这是与 psycopg2 一起使用的代码。

class PostgresDb(object):
    def __init__(self, host, port, name, user, password, connect=True):
        self.host = host
        self.port = port
        self.name = name
        self.user = user
        self.password = password
        self.connection = None
        self.cursor = None
        if connect:
            self.connect()

    def __str__(self):
        return ' '.join(map(str, [self.host,
                                  self.port,
                                  self.name,
                                  self.user]))

    def connect(self):
        try:
            self.connection = psycopg2.connect(host=self.host,
                                               port=self.port,
                                               user=self.user,
                                               password=self.password,
                                               database=self.name)
            self.cursor = self.connection.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)

        except psycopg2.DatabaseError as e:
            print e
            return e.pgerror

    def execute(self, query,  commit=True, repeat=True):
        if self.connection is None:
            self.connect()
        try:
            self.cursor.execute(query)
            if commit:
                self.connection.commit()
        except psycopg2.Error as e:
            print e
            self.connection = None
            return repeat and self.execute(query, commit=commit, repeat=False)
        else:
            return True

我做错了什么?

也许您知道为什么需要这么长时间。

最佳答案

根据您的分析结果,您似乎提交了数千个事务并为每个提交产生了相关的开销(对 herehere 进行了更深入的讨论)。

如果您的要求不一定规定这种细粒度的事务边界,您可能有的一个选择是将多个插入一起批处理到一个事务中,然后为该批处理执行一次 commit()。对于您在此处发布的内容,这可能等同于这种愚蠢的近似值:

db = PostgresDb(...your connection stuff here...)
#
# Other stuff happens, including determining your INSERT queries
#
for query in my_insert_queries[:-1]:
  db.execute(query, commit=False)
db.execute(my_insert_queries[-1], commit=True)

我敢肯定有一百万种方法可以将这个洋葱切成丁,具体取决于您的其余代码的样子 - 建议的核心是减少已提交事务的数量。

关于python - 为什么 psycopg2 对我这么慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28116205/

相关文章:

postgresql - 如何将新 token 添加到 PostgreSQL 中?

postgresql - 如何解决错误: could not access file "pglogical": No such file or directory

iphone - iOS6 iPad运行应用数量会影响内存警告频率吗?

java - 如何检测在 Netbeans 中进行分析时未显示的内存泄漏?

postgresql - 非标准导入 github.com/lib/pq"in statdard package

ios - Xcode仪器可以在真正的Apple Watch设备上运行吗?

python - scrapy 错误 :exceptions. ValueError:请求 url 中缺少方案:

命令行上的 Python 模块

python - 属性错误 : 'module' object has no attribute 'request'

python - 如何使用麦克风作为音源检测音高?