在Ubuntu上对Python代码进行性能优化,可以从多个方面入手。以下是一些常用的方法和工具:
a. cProfile
cProfile
是Python内置的性能分析模块,可以帮助你找出代码中的瓶颈。
python -m cProfile -o output.prof your_script.py
然后使用 pstats
模块或可视化工具如 pyprof2calltree
或 SnakeViz
来查看分析结果。
pip install snakeviz
python -m snakeviz output.prof
b. timeit
timeit
模块用于测量小段代码的执行时间。
import timeit
print(timeit.timeit('your_function()', globals=globals(), number=1000))
a. PyPy PyPy 是一个兼容CPython的JIT编译器,通常比CPython快很多。
sudo apt update
sudo apt install pypy3
pypy3 your_script.py
b. Numba Numba 是一个针对Python和NumPy的JIT编译器,特别适合数值计算。
from numba import jit
@jit(nopython=True)
def your_function():
# 你的代码
pass
a. 多线程
Python 的 threading
模块可以用于I/O密集型任务。
import threading
def worker():
# 你的任务
threads = []
for i in range(5):
t = threading.Thread(target=worker)
threads.append(t)
t.start()
for t in threads:
t.join()
b. 多进程
对于CPU密集型任务,使用 multiprocessing
模块可以更好地利用多核CPU。
from multiprocessing import Pool
def worker(x):
return x * x
if __name__ == '__main__':
with Pool(4) as p:
results = p.map(worker, range(10))
对于I/O密集型任务,使用 asyncio
可以提高性能。
import asyncio
async def worker():
# 你的异步任务
await asyncio.sleep(1)
async def main():
tasks = [worker() for _ in range(10)]
await asyncio.gather(*tasks)
asyncio.run(main())
对于性能要求极高的部分,可以考虑用C语言编写扩展模块。
// example.c
#include <Python.h>
static PyObject* add(PyObject* self, PyObject* args) {
int a, b;
if (!PyArg_ParseTuple(args, "ii", &a, &b)) {
return NULL;
}
return Py_BuildValue("i", a + b);
}
static PyMethodDef ExampleMethods[] = {
{"add", add, METH_VARARGS, "Add two integers."},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef examplemodule = {
PyModuleDef_HEAD_INIT,
"example",
NULL,
-1,
ExampleMethods
};
PyMODINIT_FUNC PyInit_example(void) {
return PyModule_Create(&examplemodule);
}
编译并安装:
gcc -I/usr/include/python3.8 -fPIC -shared example.c -o example.so
然后在Python中使用:
import example
print(example.add(1, 2))
对于重复计算的结果,可以使用缓存来提高性能。
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
有些库比其他库更高效。例如,对于数值计算,NumPy通常比纯Python代码快得多。
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr * 2)
通过这些方法,你应该能够在Ubuntu上显著提高Python代码的性能。