PyPy is a fast, compliant alternative implementation of the Python language (2.7.13 and 3.5.3). It has several advantages and distinct features:
- Speed: thanks to its Just-in-Time compiler, Python programs often run faster on PyPy. (What is a JIT compiler?)
- “If you want your code to run faster, you should probably just use PyPy.” — Guido van Rossum (creator of Python)
- Memory usage: memory-hungry Python programs (several hundreds of MBs or more) might end up taking less space than they do in CPython.
- Compatibility: PyPy is highly compatible with existing python code. It supports cffi and can run popular python libraries like twisted and django.
- Stackless: PyPy comes by default with support for stackless mode, providing micro-threads for massive concurrency.
从PyPy官方的介绍中可以看出它是Python语言的替代实现,比CPython更快,因为它是基于JIT技术的,并且使用更少的内存,同时还几乎提供了所有的内置模块。
既然这么好,那我们自然会想到用PyPy来对重构过的代码再做一次性能提升的尝试。
PyPy可以直接从官网上下载 http://pypy.org/download.html
提升性能,肯定要使用JIT版本,同时为了避免某些动态库无法找到的问题,推荐大家使用类似于pypy-5.10.0-linux_x86_64-portable.tar.bz2这样的portable版本,直接解压就可以使用。
PyPy贴心地内置了VirtualEnv工具,你可以用它直接生成专用的PyPy工作环境。
然后,你可能需要先使用CPython的pip命令导出项目pip安装的包到requirements.txt
pip freeze > requirements.txt
然后到PyPy工作环境的bin目录下,使用requirements.txt为PyPy安装pip包
./pip install -r requirements.txt
使用PyPy执行你的程序吧
./pypy log_generator.py
资料上说,对于计算密集型的程序,PyPy一般能够将性能提升一个数量级。而我们的测试模拟器,其实是IO密集型的程序,实测下来,性能大致提升了2倍以上。
看到这里,相信您已经了解如何使用PyPy提升Python程序性能了。
当然,我们的模拟器也顺利地能够支持模拟100w节点在线了~