在Google Cloud Run上缓慢导入numpy和pandas



我正在开发一个API,并将其部署在Google Cloud Run上。

有一个预启动python脚本导入pandas和numpy。当我对导入进行计时时,在Cloud Run上numpy大约需要2秒,pandas大约需要4秒,而在我的本地机器上不到0.5秒。

我使用python:3.8-alpine作为我的基本图像,以建立我的docker容器。(虽然我也试过几张非阿尔卑斯山的照片……)

这是Dockerfile

FROM python:3.8-alpine
COPY requirements.txt ./
RUN apk add --no-cache --virtual build-deps g++ gcc gfortran make libffi-dev openssl-dev file build-base 
&& apk add --no-cache libstdc++ openblas-dev lapack-dev  
&& pip install --no-cache-dir uvicorn gunicorn fastapi 
&& CFLAGS="-g0 -Wl,--strip-all -I/usr/include:/usr/local/include -L/usr/lib:/usr/local/lib" 
&& pip install --no-cache-dir --compile --global-option=build_ext --global-option="-j 16" -r requirements.txt 
&& rm -r /root/.cache 
&& find /usr/local/lib/python3.*/ -name 'tests' -exec rm -r '{}' + 
&& find /usr/local/lib/python3.*/site-packages/ ( -type d -a -name test -o -name tests ) -o ( -type f -a -name '*.pyc' -o -name '*.pyo' ) -exec rm -r '{}' + 
&& find /usr/local/lib/python3.*/site-packages/ -name '*.so' -print -exec /bin/sh -c 'file "{}" | grep -q "not stripped" && strip -s "{}"' ; 
&& find /usr/lib/ -name '*.so' -print -exec /bin/sh -c 'file "{}" | grep -q "not stripped" && strip -s "{}"' ; 
&& find /usr/local/lib/ -name '*.so' -print -exec /bin/sh -c 'file "{}" | grep -q "not stripped" && strip -s "{}"' ; 
&& rm -rf /usr/local/lib/python*/ensurepip 
&& rm -rf /usr/local/lib/python*/idlelib 
&& rm -rf /usr/local/lib/python*/distutils/command 
&& rm -rf /usr/local/lib/python*/lib2to2 
&& rm -rf /usr/local/lib/python*/__pycache__/* 
&& rm -r /requirements.txt /databases.zip 
&& rm -rf /tmp/* 
&& rm -rf /var/cache/apk/* 
&& apk del build-deps g++ gcc make libffi-dev openssl-dev file build-base 
CMD ["python","script.py"]

让:

numpy==1.2.0
pandas==1.2.1

和执行python文件script.py:

import time
ts = time.time()
import pandas
te = time.time()
print(te-ts)

这些缓慢的进口是意料之中的吗?或者可能有一些python导入技巧?

我一直在寻找所有的stackoverflow和github问题,但没有类似于这个"问题"/"行为"。

提前感谢。

这是Python生态系统中已知的问题。

所有模块都是在运行时导入的,有些模块的大小为300-500MB

有很多人抱怨导入时间过慢。最好的线程是这个:提高Python模块导入的速度

关于Cloud Run,我已经尝试了各种方法,但没有一种方法能够大幅降低速度。

如果您想在无服务器环境中使用,或者在其他冷启动生态系统中,
请注意冷启动可以在10秒内进行量级是因为"进口"。

importing pandas took 1.42 seconds
importing numpy took 1.90 seconds
importing torch took 2.84 seconds 
importing torchvision took 0.78 seconds
importing IPython took 1.22 seconds
importing sklearn took 1.51 seconds
importing import dask took 0.74 seconds

尝试1:

没有办法将CPU提升到最大

尝试2:

重写导入为:

时速度没有提高
pd = imp.load_module("pandas",None,"/usr/local/lib/python3.10/site-packages/pandas",('','',5))

这样,解释器会跳过"查找"。相位,但时间仍然是一样的,所以没有比这更快的速度。

尝试3:

在编译

时使用install requirements没有好处
RUN python -m pip install --no-cache-dir --compile -r requirements-prod.txt
RUN python -m compileall .

我甚至探索了容器,并且为所有模块和应用程序代码构建了__pycache__,但在冷启动时间上没有改进。

简介:

关于延迟加载建议的一个很好的阅读在这里

最新更新