python 代碼性能分析 庫

問題描述

一、Python開發的程序在使用過程當中很慢,想肯定下是哪段代碼比較慢;python

二、Python開發的程序在使用過程當中佔用內存很大,想肯定下是哪段代碼引發的;git

 

解決方案

使用profile分析分析cpu使用狀況

能夠使用profile和cProfile對python程序進行分析,這裏主要記錄下cProfile的使用,profile參考cProfile便可。github

假設有以下代碼須要進行分析(cProfileTest1.py):函數

#! /usr/bin/env python
#-*- coding:utf-8 -*-

def foo():
    sum = 0
    for i in range(100):
        sum += i
    return sum

if __name__ == "__main__" :
    foo()

能夠經過如下兩種使用方式進行分析:spa

一、不修改程序code

分析程序:blog

python -m cProfile -o test1.out cProfileTest1.py

查看運行結果:排序

python -c "import pstats; p=pstats.Stats('test1.out'); p.print_stats()"

查看排序後的運行結果:ip

python -c "import pstats; p=pstats.Stats('test1.out'); p.sort_stats('time').print_stats()"

二、修改程序內存

加入以下代碼:

#! /usr/bin/env python
#-*- coding:utf-8 -*-

def foo():
    sum = 0
    for i in range(100):
        sum += i
    return sum
    
if __name__ == "__main__" :
    import cProfile 
    cProfile.run("foo()") 
    exit(0)

運行效果以下:

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 cProfileTest2.py:4(foo)
     1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
     1    0.000    0.000    0.000    0.000 {range}

結果說明:

「」「
ncalls : 函數的被調用次數
tottime :函數總計運行時間,除去函數中調用的函數運行時間
percall :函數運行一次的平均時間,等於tottime/ncalls
cumtime :函數總計運行時間,含調用的函數運行時間
percall :函數運行一次的平均時間,等於cumtime/ncalls
filename:lineno(function) 函數所在的文件名,函數的行號,函數名
」「」

使用memory_profiler分析內存使用狀況

須要安裝memory_profiler 

pip install psutil
pip install memory_profiler

假設有以下代碼須要進行分析:

def my_func():
    a = [1] * (10*6)
    b = [2] * (10*7)
    del b
    return a

使用memory_profiler是須要修改代碼的,這裏記錄下如下兩種使用方式:

一、不導入模塊使用

#! /usr/bin/env python
#-*- coding: utf-8 -*-

# use : python -m memory_profiler test1.py

@profile
def my_func():
    a = [1] * (10*6)
    b = [2] * (10*7)
    del b
    return a
    
if __name__ == "__main__" :
    my_func()
    

profile分析:

python -m memory_profiler test1.py

二、導入模塊使用

from memory_profiler import profile

@profile
def my_func():
    a = [1] * (10*6)
    b = [2] * (10*7)
    del b
    return a

完整代碼以下:

直接運行程序便可進行分析。

運行效果以下:

(py27env) [mike@local test]$ python test1.py
Filename: test1.py

Line #    Mem usage    Increment   Line Contents
================================================
     6     29.5 MiB      0.0 MiB   @profile
     7                             def my_func():
     8     29.5 MiB      0.0 MiB       a = [1] * (10*6)
     9     29.5 MiB      0.0 MiB       b = [2] * (10*7)
    10     29.5 MiB      0.0 MiB       del b
    11     29.5 MiB      0.0 MiB       return a
相關文章
相關標籤/搜索