其他
用 PyPy 让你的 Python 代码运行得更快!
PyPy
。如何使用PyPy安装和运行代码 PyPy与CPython在速度方面的比较 PyPy的功能及其如何使Python代码更快地运行 本教程中的示例使用 Python 3.6 ,因为它是PyPy兼容的最新 Python 版本。
$ brew install pypy3
$ tar xf pypy3.6-v7.3.1-osx64.tar.bz2
$ ./pypy3.6-v7.3.1-osx64/bin/pypy3
Python 3.6.9 (?, Jul 19 2020, 21:37:06)
[PyPy 7.3.1 with GCC 4.2.1]
Type "help", "copyright", "credits" or "license" for more information.
script.py
的Python文件,并将以下代码放入其中:total = 0
for i in range(1, 10000):
for j in range(1, 10000):
total += i + j
print(f"The result is {total}")
import time
start_time = time.time()
total = 0
for i in range(1, 10000):
for j in range(1, 10000):
total += i + j
print(f"The result is {total}")
end_time = time.time()
print(f"It took {end_time-start_time:.2f} seconds to compute")
第3行将当前时间保存到变量 start_time
。第5至8行运行循环。 第10行打印结果。 第12行将当前时间保存为 end_time
。第13行打印开始时间和结束时间之间的差值,以显示运行脚本所需的时间。
$ python3.6 script.py
The result is 999800010000
It took 20.66 seconds to compute
$ pypy3 script.py
The result is 999800010000
It took 0.22 seconds to compute
class A(object):
pass
a = A()
a.some_property = a
del a
import time
start_time = time.time()
for i in range(100):
print(i)
end_time = time.time()
print(f"It took {end_time-start_time:.10f} seconds to compute")
PyPy是什么? 如何安装PyPy并使用它运行脚本 PyPy与CPython在速度方面的比较 PyPy的功能及其如何提高程序速 在哪些情况下PyPy会有局限性
长按扫码添加“Python小助手”
一起讨论PyPy!
▼点击成为社区会员 喜欢就点个在看吧