技术文章和资源

技术文章(时间排序)

热门类别

Python PHP MySQL JDBC Linux

Python 中的性能分析

pythonserver side programmingprogramming

在 Python 中,性能分析是衡量程序不同部分性能的方法,用于检查和识别优化和瓶颈区域。我们有许多工具可以对 Python 代码执行性能分析,包括内置模块、库和 IDE(集成开发环境)。Python 代码的性能分析有多种类型,让我们逐一了解。

使用行性能分析

行性能分析是用于测量程序中每行执行时间的技术。它帮助我们识别哪一行执行时间更长,并识别紧密循环或其他关键性能部分的代码。在 Python 中,我们使用 line_profiler 工具来执行行性能分析。

首先,我们必须使用下面的代码行在我们的 Python 环境中安装 Line_profiler 工具。

pip install line_profiler

输出

Collecting line_profilerNote: you may need to restart the kernel to use updated packages.

  Downloading line_profiler-4.0.3-cp39-cp39-win_amd64.whl (83 kB)
     ---------------------------------------- 83.6/83.6 kB 1.6 MB/s eta 0:00:00
Installing collected packages: line_profiler
Successfully installed line_profiler-4.0.3

现在使用 line_profiler 工具检查给定 python 代码的分析,以下是语法。

import line_profiler
line_profiler(python_code)

示例

在此示例中,我们将使用 line_profiler() 工具检查每行代码的执行时间。此模块将 python 代码作为输入,并使用 print_stats() 函数返回时间作为输出。

from line_profiler import LineProfiler
def add(a,b):
   out = a + b
   print("The sum of a and b:", out)
out = LineProfiler(add(10,30))
out.print_stats()

输出

Using Function profiling

使用函数分析

函数分析是一种允许您测量程序中各个函数或方法的执行时间的技术。这可以帮助我们确定哪些函数的执行时间最长,并且还有助于在更高级别优化代码。 Python 中用于函数分析的一个内置模块是 cProfile。

cProfile 模块的 run() 函数计算用户定义函数执行所需的时间。

语法

以下是使用 cProfile.run() 的语法。

cProfile.run(function_name)

示例

在此示例中,我们尝试将字符串格式的函数名称传递给 cProfile 模块的 run() 函数,然后它返回所有执行统计信息。

import cProfile
a = input("Enter the text to be displayed: ")
def display(a):
   print(a)
cProfile.run('display')

输出

Enter the text to be displayed: Welcome to Tutorialspoint.com
         3 function calls in 0.000 seconds

   Ordered by: standard name

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

使用内存分析

内存分析是另一种帮助用户测量程序在执行时间内使用的内存量的技术。这可以帮助我们识别内存泄漏或其他影响代码性能的内存相关问题。

memory_profiler 模块中有 profile() 函数,用于测量内存使用情况。

如果我们是第一次使用此模块,则必须使用以下代码将其安装在我们的 python 环境中。

pip install memory_profiler

安装后将显示消息。收集 memory_profiler

Downloading memory_profiler-0.61.0-py3-none-any.whl (31 kB)
Requirement already satisfied: psutil in c:\users\niharikaa\anaconda3\lib\site-packages (from memory_profiler) (5.9.0)
Installing collected packages: memory_profiler
Successfully installed memory_profiler-0.61.0

语法

使用 memory_profiler 的语法如下。

python -m memory_profiler file_name
mprof run file_name

示例

如果我们想获取内存分析执行代码的静态分析,我们必须创建一个 python 文件,然后需要通过将 python 文件与 memory_profiler 一起传递来在命令提示符中执行。

以下是保存在 python_sample.py 文件中的代码。

from memory_profiler import profile
@profile
def display():
   a = "Welcome to the Tutorialspoint website"
   print(a)
display()

我们需要在命令提示符中执行下面提到的代码行来获取内存静态信息

mprof run python_sample.py

输出

mprof: Sampling memory every 0.1s
running new process
running as a Python program...

相关文章