测量Python代码的CPU使用率,通过CMD运行

问题描述 投票:0回答:1

我创建了一个用 Python 代码编写的工具,我想测量我的代码使用 CPU 的百分比。

有办法做到这一点吗?

我在网上尝试了几种解决方案,它只是打印当前的CPU使用率(如任务管理器中看到的那样)。

我希望能够专门查看正在运行的 Python 代码的 CPU 使用情况。

python statistics cpu cpu-usage
1个回答
0
投票

要获取当前程序(您的Python脚本)的CPU,您可以使用psutil的Process类

def get_cpu_percent():
  process = psutil.Process()         ## By default gets the Process Object of current program
  cpu_usage = process.cpu_percent()  ## Gives the CPU percentage Usage
  return cpu_usage

print("CPU usage of Current Program:", get_cpu_percent())
© www.soinside.com 2019 - 2024. All rights reserved.