【问题标题】:How to calculate the amount of CPU and memory used by a python script?如何计算python脚本使用的CPU和内存量?
【发布时间】:2020-06-16 08:39:22
【问题描述】:

我编写了一个用于处理 syslog 的脚本,我需要计算 CPU 使用量和该脚本使用的内存以完成它。 有没有可以用来完成上述任务的包?

我不是在寻找整个系统当前的 CPU 使用率,而是当前运行的 python 脚本使用了多少 CPU 和 RAM。

如果我运行脚本,完成它需要多少时间以及在该时间间隔内它使用的 RAM 和 CPU 量。

我是 python 概念的新手,很难理解这一点。有什么方法可以做到吗?

提前致谢:)

【问题讨论】:

标签: python memory cpu-usage


【解决方案1】:

您可以使用一种称为 profiling 的技术和一些功能,例如timeit 用于计算脚本的性能以及运行它们所需的时间。 例如,看看这个: How can you profile a Python script?

【讨论】:

    【解决方案2】:

    使用psutil:

    import psutil
    # gives a single float value
    psutil.cpu_percent()
    # gives an object with many fields
    psutil.virtual_memory()
    # you can convert that object to a dictionary 
    dict(psutil.virtual_memory()._asdict())
    

    使用pip install psutilDocumentation安装psutil

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      • 1970-01-01
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      相关资源
      最近更新 更多