一直以来,都说Python性能很不好,那怎么解决这个问题呢?今天忽然看到Python有个JIT编译器,赶紧撸一把试试
pypy安装
因系统是CentorOS
,故而安装也就是一行命令的事情:
rpm -ivh http://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/e/epel-release-7-11.noarch.rpm
pypy的pip安装
因为pypy
的pip
与Anaconda
的pip
不能复用,故而必须要重新安装,
先拿到get-pip.py
文件,一行命令解决:
wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py
然后安装get-pip.py
,
pypy get-pip.py --user
--user
是为了加上安装权限,否则有时候work
权限或者非管理员用户无法安装。
安装完成后会有一个安装位置提示,
WARNING: The script wheel is installed in '/**/bin' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
此时进入'/**/bin'
会有pip
安装选项。
验证pypy安装
直接在命令行里输入pypy
,如果进入了Python
界面且有类似
[PyPy <你的pypy版本号> with GCC <你的GCC版本号>] on <你的操作系统类型>
这种提示信息,表示安装完成。
PyPy和Python的性能对比
假设循环**次,每一次循环都取一个随机数。
将下列代码命名为test_get_random.py
并保存:
import time
import random
start_time = time.time()
cycle_number = 10000000
def test_get_random(cycle_number):
for i in range(0, cycle_number):
random.random()
test_get_random(cycle_number)
end_time = time.time()
print ("run time is {}".format( end_time - start_time))
其中,cycle_number
可变。分别测试pypy test_get_random.py
和Python test_get_random.py
的性能。测试结果如下:
cycle_number | pypy_run_time | python_run_time |
---|---|---|
1000 | 0.000450134277344 | 0.000210046768188 |
10000000 | 0.164098978043 | 0.892430067062 |
当cycle_number
比较小时,Python
执行占优势。一旦复杂,cycle_number
比较大时,pypy
占优势。一般系统都会要比这复杂,因此,pypy
执行Python
代码有很大优势。
安装包
pypy
和pypy-pip
安装好之后,怎么样安装我们要用的package
呢?
其实进入安装get-pip.py
的安装目录后,直接使用pip install package
就好了。