Python程序内存代码检测

2018-08-22
python对于内存的操作,社区开发了一款比较强大的专门用于检测代码内存使用率的模块,memory_profile是一个使用较为简单的,并且可视化、比较直观的工具模块,可在黑窗口内通过pip工具安装:

pip install memory_profile

通过在测试函数或类型钱添加@profile注解,让内存分析模块可以直接进行代码运行监测,修改上一节代码如下:

from memory_profiler import profile 

@profile 
def chg_data_1(x): 
    x = 12 
    print("method: {}".format(x)) 
 
@profile 
def chg_data_2(y): 
    y.append("hello") 
    print("method: {}".format(y)) 

if __name__ == "__main__": 
    a = 10 
    chg_data_1(a)# 实际参数传递不可变类型
 
    print("main:", a) # 这里 a
是多少 ? 
 
    b = [1,2,3] 
    chg_data_2(b)# 实际参数传递可变类型
 
    print("main:", b) # 这里的 b
是多少 ? 

执行结果如下:

method: 12 
Filename: /Users/wenbinmu/workspace/work_py_spider/case_adv/demo08_内存分析.py 
 
Line #    Mem usage    Increment   Line Contents 
================================================ 
     3     12.5 MiB     12.5 MiB   @memory_profiler.profile 
     4                             def chg_data_1(x): 
     5     12.5 MiB      0.0 MiB       x = 12 
     6     12.5 MiB      0.0 MiB       print("method: {}".format(x)) 
 
 
main: 10 
method: [1, 2, 3, 'hello'] 
Filename: /Users/wenbinmu/workspace/work_py_spider/case_adv/demo08_内存分析.py 
 
Line #    Mem usage    Increment   Line Contents 
================================================ 
     8     12.5 MiB     12.5 MiB   @memory_profiler.profile 
     9                             def chg_data_2(y): 
    10     12.5 MiB      0.0 MiB       y.append("hello") 
    11     12.5 MiB      0.0 MiB       print("method: {}".format(y)) 
 
 
main: [1, 2, 3, 'hello'] 
 
Process finished with exit code 0 

2.3 操作符号:
  ‘is’ , ‘==’,的使用
  在程序执行的过程中,可以通过以上两个操作符号,判断对象和对象之间的关系,返回True或者False。
  A is B:判断对象A和对象B是否同一个内存地址,即是否同一个内存储对象
  A == B:判断A中的内容是否和B中的内容一致
  不论是基本类型的数据,还是内容复杂的对象,都可以通过对象判断符号'is',和内容判断符号 '==' 进行确认。


可变数据类型的内存地址判断


image.png

组合数据类型的数据判断
  创建的每个组合数据类型的对象都是独立的,如下面的代码中a, b变量中分别存放了两个不同的列表类型对象,所以is判断是False,但是值又是相同的所以==判断True:


image.png

你可能感兴趣的:(Python程序内存代码检测)