为什么 PyMongo 脚本至少需要 500 毫秒才能执行?

Why do PyMongo scripts take a minimum of 500ms to execute?

这个简单的脚本 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

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

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

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

MongoClient__init__:

中初始化一个 PeriodicExecutor
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