62 lines
1.7 KiB
C++
62 lines
1.7 KiB
C++
#include "gpu_monitor.h"
|
|
#include <iostream>
|
|
#include <memory>
|
|
|
|
GpuMonitor::GpuMonitor() : impl_(std::make_unique<Impl>()) {}
|
|
|
|
GpuMonitor::~GpuMonitor() {}
|
|
|
|
bool GpuMonitor::isReady() const {
|
|
return impl_ && impl_->ready_;
|
|
}
|
|
|
|
void GpuMonitor::setEnabled(bool enabled) {
|
|
if (impl_) {
|
|
impl_->enabled_ = enabled;
|
|
}
|
|
}
|
|
|
|
bool GpuMonitor::isEnabled() const {
|
|
return impl_ && impl_->enabled_;
|
|
}
|
|
|
|
bool GpuMonitor::getGpuStats(GpuStats &stats) {
|
|
if (!impl_ || !impl_->enabled_) {
|
|
return false;
|
|
}
|
|
|
|
if (!impl_->ready_) {
|
|
// Try to initialize
|
|
if (!impl_->initialize()) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
if (!impl_ || !impl_->device_) {
|
|
return false;
|
|
}
|
|
|
|
// Get utilization rate
|
|
nvmlUtilization_t utilizationRate = {0, 0};
|
|
nvmlReturn_t result = nvmlDeviceGetUtilizationRates(impl_->device_, &utilizationRate);
|
|
if (result != NVML_SUCCESS) {
|
|
std::cerr << "Failed to get GPU utilization: " << nvmlErrorString(result) << std::endl;
|
|
return false;
|
|
}
|
|
stats.utilizationPercent = static_cast<double>(utilizationRate.gpu);
|
|
|
|
// Get memory info
|
|
nvmlMemory_t memoryInfo;
|
|
result = nvmlDeviceGetMemoryInfo(impl_->device_, &memoryInfo);
|
|
if (result != NVML_SUCCESS) {
|
|
std::cerr << "Failed to get GPU memory info: " << nvmlErrorString(result) << std::endl;
|
|
return false;
|
|
}
|
|
|
|
// NVML returns memory in bytes, convert to MB
|
|
stats.memoryUsedMB = static_cast<double>(memoryInfo.used) / (1024 * 1024);
|
|
stats.memoryTotalMB = static_cast<double>(memoryInfo.total) / (1024 * 1024);
|
|
stats.deviceIndex = 0; // Currently only supporting default GPU
|
|
|
|
return true;
|
|
} |