python - 为什么 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。
解决方案
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
推荐阅读
- python - 加密凭证进行rest api get方法调用
- owl-carousel-2 - Owl Carousel 忽略了项目选项
- python-3.x - Zip() 将列表组合成一个元组
- java - 为什么我们需要在休眠的@OneToMany 注释侧中使用辅助方法?
- pygame - 我需要帮助我无法在 pygame 中加载图像我的图像在正确的位置
- mit-scratch - 如何不从头开始
- html - 如何更改自述文件 png 大小
- python - Odoo xml树视图未显示所有预期结果
- sharepoint - 如何使用文件夹路径和 Microsoft Graph API 1.0 上传文件
- reactjs - 在 redux 存储中存储访问令牌或密钥