Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add: GPU使用率取得関数の追加 #7

Merged
merged 1 commit into from
Sep 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,10 @@
"editor.defaultFormatter": "rust-lang.rust-analyzer",
"editor.formatOnSave": true,
"editor.inlayHints.enabled": "off"
}
},
"cSpell.words": [
"consts",
"nvapi",
"tauri"
]
}
4 changes: 2 additions & 2 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ tauri = { version = "1.6.5", features = [] }
sysinfo = "0.31.3"
tauri-plugin-window-state = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" }
nvapi = "=0.1.4"
tokio = { version = "1", features = ["full"] }
tokio = { version = "1.40.0", features = ["full"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", default-features = true, features = ["env-filter"] }
chrono = "0.4"
Expand Down
6 changes: 5 additions & 1 deletion src-tauri/src/commands/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ impl Default for Settings {
Self {
language: "en".to_string(),
theme: "dark".to_string(),
display_targets: vec![hardware::HardwareType::CPU, hardware::HardwareType::Memory],
display_targets: vec![
hardware::HardwareType::CPU,
hardware::HardwareType::Memory,
hardware::HardwareType::GPU,
],
}
}
}
Expand Down
63 changes: 6 additions & 57 deletions src-tauri/src/commands/hardware.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::services::graphic_service;
use crate::{log_debug, log_error, log_internal, log_warn};
use nvapi;
use nvapi::UtilizationDomain;
use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use std::thread;
Expand Down Expand Up @@ -64,9 +63,11 @@ pub fn get_memory_usage(state: tauri::State<'_, AppState>) -> i32 {
/// - return: `i32` GPU使用率(%)
///
#[command]
pub fn get_gpu_usage(state: tauri::State<'_, AppState>) -> i32 {
let gpu_usage = state.gpu_usage.lock().unwrap();
*gpu_usage as i32
pub async fn get_gpu_usage() -> Result<i32, String> {
match graphic_service::get_nvidia_gpu_usage().await {
Ok(usage) => Ok((usage * 100.0).round() as i32),
Err(e) => Err(format!("Failed to get GPU usage: {:?}", e)),
}
}

///
Expand Down Expand Up @@ -187,56 +188,4 @@ pub fn initialize_system(

thread::sleep(Duration::from_secs(SYSTEM_INFO_INIT_INTERVAL));
});

///
/// TODO GPU使用率を取得する
///
#[allow(dead_code)]
fn get_gpu_usage() -> Result<f32, nvapi::Status> {
log_debug!("start", "get_gpu_usage", None::<&str>);

let gpus = nvapi::PhysicalGpu::enumerate()?;

print!("{:?}", gpus);

if gpus.is_empty() {
log_warn!("not found", "get_gpu_usage", Some("gpu is not found"));
tracing::warn!("gpu is not found");
return Err(nvapi::Status::Error); // GPUが見つからない場合はエラーを返す
}

let mut total_usage = 0.0;
let mut gpu_count = 0;

for gpu in gpus.iter() {
let usage = match gpu.usages() {
Ok(usage) => usage,
Err(e) => {
log_error!("usages_failed", "get_gpu_usage", Some(e.to_string()));
return Err(e);
}
};

if let Some(gpu_usage) = usage.get(&UtilizationDomain::Graphics) {
let usage_f32 = gpu_usage.0 as f32 / 100.0; // Percentage を f32 に変換
total_usage += usage_f32;
gpu_count += 1;
}
}

if gpu_count == 0 {
log_warn!(
"no_usage",
"get_gpu_usage",
Some("No GPU usage data collected")
);
return Err(nvapi::Status::Error); // 使用率が取得できなかった場合のエラーハンドリング
}

let average_usage = total_usage / gpu_count as f32;

log_debug!("end", "get_gpu_usage", None::<&str>);

Ok(average_usage)
}
}
121 changes: 61 additions & 60 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,60 +1,61 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#[macro_use]

mod commands;
mod enums;
mod utils;

use commands::config;
use commands::hardware;

use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use sysinfo::System;

fn main() {
utils::logger::init();

let app_state = config::AppState::new();

let system = Arc::new(Mutex::new(System::new_all()));
let cpu_history = Arc::new(Mutex::new(VecDeque::with_capacity(60)));
let memory_history = Arc::new(Mutex::new(VecDeque::with_capacity(60)));
let gpu_usage = Arc::new(Mutex::new(0.0));
let gpu_history = Arc::new(Mutex::new(VecDeque::with_capacity(60)));

let state = hardware::AppState {
system: Arc::clone(&system),
cpu_history: Arc::clone(&cpu_history),
memory_history: Arc::clone(&memory_history),
gpu_usage: Arc::clone(&gpu_usage),
gpu_history: Arc::clone(&gpu_history),
};

hardware::initialize_system(
system,
cpu_history,
memory_history,
gpu_usage,
gpu_history,
);

tauri::Builder::default()
.plugin(tauri_plugin_window_state::Builder::default().build())
.manage(state)
.manage(app_state)
.invoke_handler(tauri::generate_handler![
hardware::get_cpu_usage,
hardware::get_memory_usage,
hardware::get_gpu_usage,
hardware::get_cpu_usage_history,
hardware::get_memory_usage_history,
hardware::get_gpu_usage_history,
config::commands::set_language,
config::commands::set_theme,
config::commands::get_settings
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#[macro_use]

mod commands;
mod enums;
mod services;
mod utils;

use commands::config;
use commands::hardware;

use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use sysinfo::System;

fn main() {
utils::logger::init();

let app_state = config::AppState::new();

let system = Arc::new(Mutex::new(System::new_all()));
let cpu_history = Arc::new(Mutex::new(VecDeque::with_capacity(60)));
let memory_history = Arc::new(Mutex::new(VecDeque::with_capacity(60)));
let gpu_usage = Arc::new(Mutex::new(0.0));
let gpu_history = Arc::new(Mutex::new(VecDeque::with_capacity(60)));

let state = hardware::AppState {
system: Arc::clone(&system),
cpu_history: Arc::clone(&cpu_history),
memory_history: Arc::clone(&memory_history),
gpu_usage: Arc::clone(&gpu_usage),
gpu_history: Arc::clone(&gpu_history),
};

hardware::initialize_system(
system,
cpu_history,
memory_history,
gpu_usage,
gpu_history,
);

tauri::Builder::default()
.plugin(tauri_plugin_window_state::Builder::default().build())
.manage(state)
.manage(app_state)
.invoke_handler(tauri::generate_handler![
hardware::get_cpu_usage,
hardware::get_memory_usage,
hardware::get_gpu_usage,
hardware::get_cpu_usage_history,
hardware::get_memory_usage_history,
hardware::get_gpu_usage_history,
config::commands::set_language,
config::commands::set_theme,
config::commands::get_settings
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
71 changes: 71 additions & 0 deletions src-tauri/src/services/graphic_service.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
use crate::{log_debug, log_error, log_info, log_internal, log_warn};
use nvapi;
use nvapi::UtilizationDomain;
use tokio::task::spawn_blocking;
use tokio::task::JoinError;

///
/// GPU使用率を取得する(NVAPI を使用)
///
pub async fn get_nvidia_gpu_usage() -> Result<f32, nvapi::Status> {
let handle = spawn_blocking(|| {
log_debug!("start", "get_nvidia_gpu_usage", None::<&str>);

let gpus = nvapi::PhysicalGpu::enumerate()?;

if gpus.is_empty() {
log_warn!(
"not found",
"get_nvidia_gpu_usage",
Some("gpu is not found")
);
tracing::warn!("gpu is not found");
return Err(nvapi::Status::Error); // GPUが見つからない場合はエラーを返す
}

let mut total_usage = 0.0;
let mut gpu_count = 0;

for gpu in gpus.iter() {
let usage = match gpu.usages() {
Ok(usage) => usage,
Err(e) => {
log_error!("usages_failed", "get_nvidia_gpu_usage", Some(e.to_string()));
return Err(e);
}
};

if let Some(gpu_usage) = usage.get(&UtilizationDomain::Graphics) {
let usage_f32 = gpu_usage.0 as f32 / 100.0; // Percentage を f32 に変換
total_usage += usage_f32;
gpu_count += 1;
}
}

log_info!(
&format!("gpu_count: {:?}", gpu_count),
"get_nvidia_gpu_usage",
None::<&str>
);

if gpu_count == 0 {
log_warn!(
"no_usage",
"get_nvidia_gpu_usage",
Some("No GPU usage data collected")
);
return Err(nvapi::Status::Error); // 使用率が取得できなかった場合のエラーハンドリング
}

let average_usage = total_usage / gpu_count as f32;

log_debug!("end", "get_nvidia_gpu_usage", None::<&str>);

Ok(average_usage)
});

handle.await.map_err(|e: JoinError| {
log_error!("join_error", "get_nvidia_gpu_usage", Some(e.to_string()));
nvapi::Status::Error
})?
}
1 change: 1 addition & 0 deletions src-tauri/src/services/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod graphic_service;