import torch
import time
def simulate_gpu_load_torch(usage_percentage, duration):
# 检查是否有可用的GPU,如果没有,将使用CPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 模拟 GPU 计算任务
data = torch.rand((1000, 1000), device=device)
result = torch.matmul(data, data)
# 控制 GPU 使用率
busy_time = duration * (usage_percentage / 100)
idle_time = duration - busy_time
start_time = time.time()
while (time.time() - start_time) < duration:
result = torch.matmul(data, data)
time.sleep(busy_time)
# 空闲时间不进行计算
time.sleep(idle_time)
# 控制 GPU 使用率为50%,持续10秒
simulate_gpu_load_torch(50, 10)