【问题标题】:How do I calculate how much CPU, RAM, energy is required to run a specific Python program?如何计算运行特定 Python 程序需要多少 CPU、RAM、能量?
【发布时间】:2020-05-26 01:33:57
【问题描述】:

假设我们想找出 Python 中使用了多少能量、CPU 和 RAM 来找出正整数的阶乘。我使用了下面的代码,但它不起作用。

MWE:

from __future__ import print_function
import psutil

n=5
fact=1
for i in range(1,n+1):
    fact=fact*i
print fact

print('CPU  % used:', psutil.cpu_percent())
print('physical memory  % used:', psutil.virtual_memory())  # physical memory usage
print('memory % used:', psutil.virtual_memory()[2])

【问题讨论】:

  • 我不认为你可以从 python 程序内部测量你使用了多少能量。我认为它不会访问所有报告您计算机能源使用情况的传感器。
  • @MichaelBykhovtsev 有什么办法吗?

标签: python cpu-usage ram energy


【解决方案1】:

您想使用psutil.Process(pid=None)。文档注意事项:

如果省略 pid,则使用当前进程 pid (os.getpid)。

因此,您可以简单地这样做:

import psutil


process = psutil.Process()
memory = process.memory_percent()
cpu = process.cpu_percent()

print(memory, cpu)

以上仅用于内存和 CPU 百分比使用。我建议您进一步阅读文档以准确了解您需要什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-04
    • 2016-03-22
    • 2015-06-27
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    相关资源
    最近更新 更多