【问题标题】:Print GPU and CPU usage in TensorFlow在 TensorFlow 中打印 GPU 和 CPU 使用率
【发布时间】:2020-02-26 14:39:14
【问题描述】:
我正在 Google Colab 上运行一些 TensorFlow 示例(这样我就可以拥有 GPU),like this one.
有没有办法在代码中打印每个训练步骤的 CPU 和 GPU 使用率,以便查看 GPU 的使用情况以及 CPU 和 GPU 之间的性能差异?
在 标准 环境中,也许我可以使用 nvidia-smi 来跟踪 GPU 使用情况,但使用笔记本时,我一次只能运行一个单元。
谢谢
【问题讨论】:
标签:
python
tensorflow
google-colaboratory
【解决方案1】:
我从 Internet 上抓取了一个 sn-p 代码。您可以随时运行 printm 函数。
# memory footprint support libraries/code
!ln -sf /opt/bin/nvidia-smi /usr/bin/nvidia-smi
!pip install gputil
!pip install psutil
!pip install humanize
import psutil
import humanize
import os
import GPUtil as GPU
GPUs = GPU.getGPUs()
# XXX: only one GPU on Colab and isn’t guaranteed
gpu = GPUs[0]
def printm():
process = psutil.Process(os.getpid())
print("Gen RAM Free: " + humanize.naturalsize( psutil.virtual_memory().available ), " | Proc size: " + humanize.naturalsize( process.memory_info().rss))
print("GPU RAM Free: {0:.0f}MB | Used: {1:.0f}MB | Util {2:3.0f}% | Total {3:.0f}MB".format(gpu.memoryFree, gpu.memoryUsed, gpu.memoryUtil*100, gpu.memoryTotal))
printm()
这是我的 Google Colab 的输出:
Gen RAM Free: 12.8 GB | Proc size: 155.7 MB
GPU RAM Free: 11441MB | Used: 0MB | Util 0% | Total 11441MB
【解决方案2】:
您需要启动一个线程来为您打印此内容。当这个线程正在运行时,您只会在其他单元格运行时看到输出。
代码:
!ln -sf /opt/bin/nvidia-smi /usr/bin/nvidia-smi
!pip install gputil
!pip install psutil
!pip install humanize
import psutil
import humanize
import os, time
import GPUtil as GPU
GPUs = GPU.getGPUs()
# XXX: only one GPU on Colab and isn’t guaranteed
gpu = GPUs[0]
def worker():
while True:
process = psutil.Process(os.getpid())
print("Gen RAM Free: " + humanize.naturalsize( psutil.virtual_memory().available `enter code here`), " I Proc size: " + humanize.naturalsize( process.memory_info().rss))
print("GPU RAM Free: {0:.0f}MB | Used: {1:.0f}MB | Util {2:3.0f}% | Total {3:.0f}MB".format(gpu.memoryFree, gpu.memoryUsed, gpu.memoryUtil*100, gpu.memoryTotal))
time.sleep(6)
import threading
t = threading.Thread(target=worker, name='Monitor')
t.start()
测试: