pythonmemory_profiler库制作器和迭代器cpu占用的时间分析

AI 摘要 / TL;DR

文章内容主要是详细介绍了pythonmemory\ profiler库制作器和迭代器cpu占用的时间分析,文章内容紧扣主题进行详尽的基本介绍,感兴趣的朋友可以了解一下 不进行计算时,生成器和list空间占用 显示结果的内涵:第一行表明已剖析编码的号码,第二列(Mem应用情况)表明实行当列后Python编译器的内存使用情

来源: https://www.ucloud.cn/yun/128837.html 作者: 89542767 发布日期: 发布于2022-12-28 16:00

文章内容主要是详细介绍了pythonmemory_profiler库制作器和迭代器cpu占用的时间分析,文章内容紧扣主题进行详尽的基本介绍,感兴趣的朋友可以了解一下

  不进行计算时,生成器和list空间占用

  import time
  from memory_profiler import profile
  profile(precision=4)
  def list_fun():
  start=time.time()
  total=([i for i in range(5000000)])
  print('iter_spend_time:',time.time()-start)
  profile(precision=4)
  def gent_func():
  gent_start=time.time()
  total=(i for i in range(5000000))
  print('gent_spend_time:',time.time()-gent_start)
  iter_fun()
  gent_func()

01.png

  显示结果的内涵:第一行表明已剖析编码的号码,第二列(Mem应用情况)表明实行当列后Python编译器的内存使用情况。第三列(增长)表明现阶段行相较于最后一行的运行内存差别。最终某列(行具体内容)打印出已讲解的编码。

  剖析:在没有来计算的情形下,目录list和迭代器会占空间,但是对于制作器不容易占空间

  当要测算,list和制作器的耗费时间和占用内存

  使用sum内置函数,list和制作器求合10000000个数据信息,listcpu占用比较大,制作器耗费时间大约是list的二倍

  import time
  from memory_profiler import profile
  profile(precision=4)
  def iter_fun():
  start=time.time()
  total=sum([i for i in range(10000000)])
  print('iter_spend_time:',time.time()-start)
  profile(precision=4)
  def gent_func():
  gent_start=time.time()
  total=sum(i for i in range(10000000))
  print('gent_spend_time:',time.time()-gent_start)
  iter_fun()
  gent_func()

02.png

  对比分析,必要时对信息进行迭代更新使用中,制作器方式的用时很长,但内存使用上还是偏少,由于应用制作器时,运行内存只存放每一次迭代计算的信息。查找原因时个人觉得,制作器的迭代计算环节中,在迭代更新数据与测算立即持续变换,对比与迭代器目标中先将它们所有储存在运行内存中(尽管占用内存,但载入比再度迭代更新要快点),因而,制作器较为耗时间,但占用内存小。

  记录数据循环系统求合500000个数据信息,迭代器和制作器循环系统得到时

  汇总:基本上与此同时成功,迭代器的占用内存比较大

  import time
  from memory_profiler import profile
  itery=iter([i for i in range(5000000)])
  gent=(i for i in range(5000000))
  profile(precision=4)
  def iter_fun():
  start=time.time()
  total=0
  for item in itery:
  total+=item
  print('iter:',time.time()-start)
  profile(precision=4)
  def gent_func():
  gent_start=time.time()
  total=0
  for item in gent:
  total+=item
  print('gent:',time.time()-gent_start)
  iter_fun()
  gent_func()
  list,迭代器和生成器共同使用sum计算5000000个数据时间比较

03.png

  总结:list+sum和迭代器+sum计算时长差不多,但生成器+sum计算的时长几乎长一倍,

  import time
  from memory_profiler import profile
  profile(precision=4)
  def list_fun():
  start=time.time()
  print('start!!!')
  list_data=[i for i in range(5000000)]
  total=sum(list_data)
  print('iter_spend_time:',time.time()-start)
  profile(precision=4)
  def iter_fun():
  start=time.time()
  total=0
  total=sum(iter([i for i in range(5000000)]))
  print('total:',total)
  print('iter_spend_time:',time.time()-start)
  profile(precision=4)
  def gent_func():
  gent_start=time.time()
  total=sum(i for i in range(5000000))
  print('total:',total)
  print('gent_spend_time:',time.time()-gent_start)
  list_fun()
  iter_fun()
  gent_func()

04.png

  综上所述,这篇文章就给大家介绍到这里了,希望可以给大家带来帮助。