在OpenWrt上可以运行Python代码(确切地说,是迷你Python ),但即使是一个简单的"Hello World“Python脚本也需要6-8秒才能运行。
根据我的调查,所有Python模块都保存在py源代码中,并在每次运行时在内存中编译。
由于大约有20个或更多的模块,而且OpenWrt运行在小型嵌入式设备上,这会导致即使是最简单的Python脚本也无法启动。
如何在OpenWrt上加速Python代码的执行?
发布于 2017-10-02 21:25:46
为了将Python脚本的速度提高10倍以上,可以选择预编译所有库并将它们写成pyc文件。
如果你不这样做,那么每次都会动态编译所有的库,这是非常耗时的cpu任务。
你需要有至少4MB可用空间的设备,因为你是在用空间换取时间。
我的诀窍是在启动时创建检查,如果有少于150个pyc文件,并且如果有将python从py编译成pyc。
# count python pyc modules and generate if needed
pyc=`find / -name *.pyc | wc -l`
if [ $pyc -lt 150 ]; then
python -m compileall
fi如果您仍然看到python执行缓慢,请检查一些python库是否未位于某些子目录中。例如,为了获得完整的运行速度,我在statup脚本中添加了python-serial目录。
# count python pyc modules and generate if needed
pyc=`find / -name *.pyc | wc -l`
if [ $pyc -lt 400 ]; then
python -m compileall
python -m compileall /usr/lib/python2.7/site-packages/serial/*.py
python -m compileall /usr/lib/python2.7/site-packages/serial/tools/*.py
python -m compileall /usr/lib/python2.7/site-
packages/serial/urlhandler/*.py
fi那就是,在OpenWrt/Lede系统上享受超快的python脚本吧!
https://stackoverflow.com/questions/42682168
复制相似问题