在Ubuntu上进行Python性能测试,你可以使用多种工具和方法。以下是一些常用的性能测试工具及其使用方法:
timeit:
import timeit
def test_function():
return sum(range(1000))
print(timeit.timeit(test_function, number=1000))
cProfile:
import cProfile
cProfile.run('test_function()')
memory_profiler:
from memory_profiler import profile
@profile
def test_function():
a = [i * i for i in range(1000000)]
test_function()
line_profiler:
pip install line_profiler
),然后使用装饰器@profile
。from line_profiler import profile
@profile
def test_function():
a = [i * i for i in range(1000000)]
test_function()
Locust:
# locustfile.py
from locust import HttpUser, task, between
class WebsiteUser(HttpUser):
wait_time = between(1, 5)
@task
def index_page(self):
self.client.get("/")
然后在终端中运行 locust -f locustfile.py
。sysbench:
sudo apt-get install sysbench
sysbench cpu --threads=4 --time=60 run
PyCharm:
通过这些工具,你可以对Python代码进行性能测试和分析,从而找出性能瓶颈并进行优化。