首页 > 解决方案 > 为什么 PyMongo 脚本至少需要 500 毫秒才能执行?

问题描述

这个简单的脚本test.py总是需要超过 500 毫秒才能执行:

import pymongo
pymongo.MongoClient(host='127.0.0.1')

像这样:

lanroth@ubuntu:~$ time python3 ./test.py 
real    0m0.608s
user    0m0.096s
sys     0m0.012s

我已经在运行 Ubunutu 16.04、Mint 19、Docker 容器中的 Mongo 或裸机的不同 Linux 机器上进行了尝试。脚本总是占用 500 毫秒以上,通常在 580 毫秒到 650 毫秒之间。

脚本退出时似乎会发生延迟,所以我的猜测是在清理连接期间,某些东西在 500 毫秒后超时。

执行以下 shell 命令time echo 'show dbs' | mongo大约需要 8 毫秒,所以我很确定这与 PyMongo 相关,而不是 MongoDB。

标签: pythonpython-3.xmongodbpymongo-3.x

解决方案


MongoClient初始化a PeriodicExecutor__init__

executor = periodic_executor.PeriodicExecutor(
    interval=common.KILL_CURSOR_FREQUENCY,
    min_interval=0.5,
    target=target,
    name="pymongo_kill_cursors_thread")

如您所见,min_interval为 0.5 秒。根据PeriodicExecutor._run方法,线程将至少休眠 0.5 秒:

def _run(self):
    while not self.__should_stop():
        try:
            if not self._target():
                self._stopped = True
                break
        except:
            with self._lock:
                self._stopped = True
                self._thread_will_exit = True

            raise

        deadline = _time() + self._interval

        while not self._stopped and _time() < deadline:
            time.sleep(self._min_interval)
            if self._event:
                break  # Early wake.

        self._event = False

直接在代码中将 0.5 更改为 0.1 可将我机器上的时间从 0.6 减少到 0.2:

(main-4hIy5yvR) ➜  main time python ./main.py
python ./main.py  0.07s user 0.02s system 15% cpu 0.596 total
(main-4hIy5yvR) ➜  main time python ./main.py
python ./main.py  0.08s user 0.02s system 49% cpu 0.203 total

推荐阅读