繁体   English   中英

在 Python 中测试期间的 CPU 利用率?

[英]CPU utilization during testing in Python?

我想在测试我的 ML model 期间(在调用predict期间)获取 cpu 使用情况。 这是我目前正在做的事情。 p是当前进程:

start = p.cpu_percent(interval=1)
y_hat = clf.predict(X_test)
print(abs(p.cpu_percent(interval=None) - start)) # prints cpu usage (%)

这是正确的方法还是有更好的方法来实现这一目标?

  1. 使用psutil建议使用psutil.virtual_memory()

     import psutil mem = psutil.virtual_memory() print(mem) svmem(total=10367352832, available=6472179712, percent=37.6, used=8186245120, free=2181107712, active=4748992512, inactive=2758115328, buffers=790724608, cached=3500347392, shared=787554304, slab=199348224) THRESHOLD = 100 * 1024 * 1024 # 100MB if mem.available <= THRESHOLD: print("warning") # you can convert that object to a dictionary dict(psutil.virtual_memory()._asdict())

  1. psutil.cpu_times(percpu=False)以命名元组的形式返回系统 CPU 时间。

     import psutil print(psutil.cpu_times()) #scputimes(user=17411.7, nice=77.99, system=3797.02, idle=51266.57, iowait=732.58, irq=0.01, softirq=142.43, steal=0.0, guest=0.0, guest_nice=0.0)

  1. os.times()返回当前的全局进程时间。 返回值为具有五个属性的 object

     import os curr_gp_times = os.times() print(curr_gp_times) # posix.times_result(user=0.03, system=0.01, children_user=0.0, children_system=0.0, elapsed=17370844.95)

编辑这可能更接近您正在寻找的内容:

  1. psutil.cpu_times(percpu=False)以命名元组的形式返回系统 CPU 时间。 每个属性代表 CPU 在给定模式下花费的秒数。

    • user:正常进程在用户模式下执行所花费的时间; 在 Linux 这也包括访客时间

    • system:在 kernel 模式下执行的进程所花费的时间

    • idle:无所事事的时间

       import psutil psutil.cpu_times() # scputimes(user=17411.7, nice=77.99, system=3797.02, idle=51266.57, iowait=732.58, irq=0.01, softirq=142.43, steal=0.0, guest=0.0, guest_nice=0.0)

假设您想在程序中使用内置函数执行操作,Python 的resource模块可能对您有用。 如果您能够安装软件包, psutil是一个不错的选择(正如 Federico 所建议的那样)。

在你的程序之外,有很多方法可以获取任意进程的 CPU 使用率。 如果您在 *nux 上并且更喜欢命令行,那么top和类似的命令应该可以完成这项工作。 在图形界面上,我个人更喜欢 KSysGuard(我在 Kubuntu 上)。 Gnome 系统监视器也可以工作。 在 Windows 上,任务管理器就足够了。

编辑: psutil似乎返回全局用法。 如果您只想使用您的进程,最好使用resourceos.times ,但如果您想要总 CPU 利用率(包括其他进程) psutil是一个更强大的解决方案。

对于resource中的 CPU 时间:

import resource

resource.getrusage()[0]  # Returns the time in seconds in user mode
# Note that this time accumulates while the program runs,
# so you might want to save its previous value each time you take a measurement

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM