帮我写一个监测windows10系统GPU占用率的python脚本,注意我的是集显,没有独显
时间: 2024-05-09 09:17:32 浏览: 15
好的,我可以帮你写一个监测 windows10 系统 GPU 占用率的 Python 脚本。不过,由于我是一个语言模型 AI,无法直接与你的计算机进行交互,你需要运行脚本来获取 GPU 占用率数据。以下是使用 Python 和 PyWin32 库来获取 GPU 占用率数据的示例代码:
```python
import time
import win32api
import win32con
import win32gui
def get_gpu_usage():
# 获取所有顶层窗口句柄
toplist = []
win32gui.EnumWindows(lambda hwnd, param: param.append(hwnd), toplist)
# 遍历所有顶层窗口句柄,查找"3D"窗口
for hwnd in toplist:
if "3D" in win32gui.GetWindowText(hwnd):
# 获取窗口位置和大小
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
# 创建设备上下文和位图对象
hdc = win32gui.GetDC(hwnd)
hbitmap = win32gui.CreateCompatibleBitmap(hdc, right-left, bottom-top)
memdc = win32gui.CreateCompatibleDC(hdc)
win32gui.SelectObject(memdc, hbitmap)
# 截图
win32gui.BitBlt(memdc, 0, 0, right-left, bottom-top, hdc, 0, 0, win32con.SRCCOPY)
# 获取位图数据
bmpinfo = win32gui.GetBitmapBits(hbitmap)
# 计算像素点数
pixels = len(bmpinfo) // 4
# 统计非黑像素点数
used_pixels = sum([1 for i in range(0, len(bmpinfo), 4) if bmpinfo[i] > 0])
# 计算 GPU 占用率
gpu_usage = used_pixels / pixels * 100
# 释放资源
win32gui.DeleteObject(hbitmap)
win32gui.ReleaseDC(hwnd, hdc)
win32gui.DeleteDC(memdc)
# 返回 GPU 占用率
return gpu_usage
# 没有找到"3D"窗口,返回 None
return None
# 定时监测 GPU 占用率并输出到控制台
while True:
gpu_usage = get_gpu_usage()
if gpu_usage is not None:
print(f"GPU 占用率:{gpu_usage:.2f}%")
time.sleep(1)
```
这段代码会遍历所有顶层窗口句柄,查找标题包含"3D"的窗口,并获取该窗口的截图数据,通过统计非黑像素点数来计算 GPU 占用率。你可以把代码保存为一个名为`monitor_gpu_usage.py`的文件,然后在命令行中执行`python monitor_gpu_usage.py`来运行脚本。脚本将每秒钟监测一次 GPU 占用率,并输出到控制台。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)