Python 性能分析的方法与工具推荐

import time

def countdown(n): while n > 0: n -= 1

第一种:

class Timer: def init(self, func=time.perf_counter): self.elapsed = 0.0 self._func = func self._start = None

def start(self):
    if self._start is not None:
        raise RuntimeError('Already started')
    self._start = self._func()

def stop(self):
    if self._start is None:
        raise RuntimeError('Not started')
    end = self._func()
    self.elapsed += end - self._start
    self._start = None

def reset(self):
    self.elapsed = 0.0

@property
def running(self):
    return self._start is not None

def __enter__(self):
    self.start()
    return self

def __exit__(self, *args):
    self.stop()

In [68]: with Timer() as t2: …: countdown(1000000) …: print(t2.elapsed) …: 0.06051115319132805

第二种:

In [27]: def profile(func): …: def wrapper( *args, **kwargs): …: start = time.time() …: func(*args, **kwargs) …: end = time.time() …: print(end - start) …: return wrapper …: In [28]: @profile …: def countdown(n): …: while n > 0: …: n -= 1 …:

In [80]: countdown(1000000) 0.0597081184387207

第三种

ipython

In [67]: %timeit countdown(1000000) 10 loops, best of 3: 59.3 ms per loop

第四种

>>> import cProfile >>> def countdown(n): … while n > 0: … n -= 1 … >>> cProfile.run(‘countdown(1000000)’) 4 function calls in 0.068 seconds

Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function) 1 0.068 0.068 0.068 0.068 <stdin>:1(countdown) 1 0.000 0.000 0.068 0.068 <string>:1(<module>) 1 0.000 0.000 0.068 0.068 {built-in method builtins.exec} 1 0.000 0.000 0.000 0.000 {method ‘disable’ of ‘_lsprof.Profiler’ objects}

使用可视化:

>>> import cProfile >>> def countdown(n): … while n > 0: … n -= 1 … >>> cProfile.run(‘countdown(1000000)’,“result”) 4 function calls in 0.068 seconds

snakeviz result


Python 性能分析的方法与工具推荐

1 回复

Python性能分析的核心是找到瓶颈。我常用的方法是先用cProfile做整体分析,再用line_profilermemory_profiler深入细节。

1. cProfile - 整体性能画像 这是标准库自带的,能快速定位耗时最多的函数。

import cProfile
import pstats

def your_function():
    # 你的代码
    pass

# 运行分析
profiler = cProfile.Profile()
profiler.enable()
your_function()
profiler.disable()

# 输出结果
stats = pstats.Stats(profiler)
stats.sort_stats('cumulative')  # 按累计时间排序
stats.print_stats(10)  # 显示前10个耗时函数

2. line_profiler - 逐行分析pip install line_profiler安装,能精确到每行代码的执行时间。

from line_profiler import LineProfiler

lp = LineProfiler()
lp.add_function(your_function)  # 要分析的函数
lp.enable()
your_function()
lp.disable()
lp.print_stats()

3. memory_profiler - 内存分析 pip install memory_profiler,分析内存使用情况。

from memory_profiler import profile

@profile
def your_function():
    # 你的代码
    pass

your_function()  # 运行时会显示每行的内存变化

4. 火焰图可视化py-spy生成火焰图更直观:

pip install py-spy
py-spy record -o profile.svg -- python your_script.py

工具选择建议:

  • 先用cProfile快速定位问题函数
  • 再用line_profiler分析具体代码行
  • 内存问题用memory_profiler
  • 复杂性能问题用火焰图

总结:从宏观到微观,先用cProfile定位,再用line_profiler深挖。

回到顶部