Spaces:
Sleeping
Sleeping
File size: 6,428 Bytes
463f868 9bd4ce5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | use engine_rust::core::logic::{CardDatabase, GameState, ACTION_SPACE};
use engine_rust::test_helpers::load_real_db;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
fn parse_deck(path: &str, db: &CardDatabase) -> Vec<i32> {
let content = std::fs::read_to_string(path).unwrap_or_else(|_| String::new());
if content.is_empty() {
return vec![];
}
let mut ids = Vec::new();
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let parts: Vec<&str> = line.split('x').map(|s| s.trim()).collect();
let no = parts[0];
let count = if parts.len() > 1 {
parts[1].parse::<usize>().unwrap_or(1)
} else {
1
};
if let Some(&id) = db.card_no_to_id.get(no) {
for _ in 0..count {
ids.push(id);
}
}
}
ids
}
/// Run a single-threaded benchmark, returns (games, steps)
fn run_single_thread(
initial_state: &GameState,
db: &CardDatabase,
duration: Duration,
seed: u64,
) -> (u64, u64) {
let mut total_games: u64 = 0;
let mut total_steps: u64 = 0;
let start = Instant::now();
let mut rng_state = seed;
// Pre-allocate action mask on stack (avoid heap alloc per step)
let mut mask = vec![false; ACTION_SPACE];
while start.elapsed() < duration {
let mut sim = initial_state.clone();
let mut steps: u64 = 0;
while !sim.is_terminal() && steps < 1000 {
// Reuse pre-allocated mask
mask.fill(false);
sim.get_legal_actions_into(db, sim.current_player as usize, &mut mask);
// Collect valid actions without heap alloc (use SmallVec-like inline)
let mut valid_count = 0u32;
let mut first_valid: i32 = -1;
for (i, &b) in mask.iter().enumerate() {
if b {
if first_valid < 0 {
first_valid = i as i32;
}
valid_count += 1;
}
}
if valid_count == 0 {
break;
}
// Xorshift RNG
rng_state ^= rng_state << 13;
rng_state ^= rng_state >> 17;
rng_state ^= rng_state << 5;
let target_idx = (rng_state as u32) % valid_count;
// Find the nth valid action
let mut count = 0u32;
let mut chosen_action = first_valid;
for (i, &b) in mask.iter().enumerate() {
if b {
if count == target_idx {
chosen_action = i as i32;
break;
}
count += 1;
}
}
let _ = sim.step(db, chosen_action);
steps += 1;
}
total_games += 1;
total_steps += steps;
}
(total_games, total_steps)
}
fn main() {
println!("=== Unified Rust CPU Benchmark (10s Challenge) ===");
let db = load_real_db();
let deck_path = if std::path::Path::new("ai/decks/muse_cup.txt").exists() {
"ai/decks/muse_cup.txt"
} else {
"../ai/decks/muse_cup.txt"
};
let p_deck = parse_deck(deck_path, &db);
let p_main = if p_deck.is_empty() {
println!(
"Warning: Could not find deck at {}, using fallback.",
deck_path
);
db.members.keys().take(50).cloned().collect()
} else {
p_deck
};
let energy_ids: Vec<i32> = db.energy_db.keys().take(10).cloned().collect();
let mut initial_state = GameState::default();
initial_state.initialize_game(
p_main.clone(),
p_main.clone(),
energy_ids.clone(),
energy_ids.clone(),
Vec::new(),
Vec::new(),
);
initial_state.ui.silent = true;
initial_state.phase = engine_rust::core::logic::Phase::Main;
let bench_duration = Duration::from_secs(10);
let num_threads = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(4);
println!("Threads: {}", num_threads);
// --- Single-threaded benchmark ---
println!("\n--- Single-Threaded ---");
let (st_games, st_steps) = run_single_thread(&initial_state, &db, bench_duration, 12345);
let st_dur = 10.0f64; // approximate
println!("Games: {}", st_games);
println!("Steps: {}", st_steps);
println!("Games/sec: {:.2}", st_games as f64 / st_dur);
println!("Steps/sec: {:.2}", st_steps as f64 / st_dur);
println!(
"Avg Steps/g: {:.1}",
st_steps as f64 / st_games.max(1) as f64
);
// --- Multi-threaded benchmark ---
println!("\n--- Multi-Threaded ({} threads) ---", num_threads);
let total_games = Arc::new(AtomicU64::new(0));
let total_steps = Arc::new(AtomicU64::new(0));
let start_time = Instant::now();
std::thread::scope(|s| {
for t in 0..num_threads {
let db_ref = &db;
let state_ref = &initial_state;
let games_ref = Arc::clone(&total_games);
let steps_ref = Arc::clone(&total_steps);
s.spawn(move || {
let seed = 12345u64.wrapping_add(t as u64 * 7919);
let (g, st) = run_single_thread(state_ref, db_ref, bench_duration, seed);
games_ref.fetch_add(g, Ordering::Relaxed);
steps_ref.fetch_add(st, Ordering::Relaxed);
});
}
});
let mt_dur = start_time.elapsed().as_secs_f64();
let mt_games = total_games.load(Ordering::Relaxed);
let mt_steps = total_steps.load(Ordering::Relaxed);
println!("Games: {}", mt_games);
println!("Steps: {}", mt_steps);
println!("Games/sec: {:.2}", mt_games as f64 / mt_dur);
println!("Steps/sec: {:.2}", mt_steps as f64 / mt_dur);
println!(
"Avg Steps/g: {:.1}",
mt_steps as f64 / mt_games.max(1) as f64
);
println!(
"Speedup: {:.2}x",
mt_steps as f64 / st_steps.max(1) as f64
);
println!("\n=== Done ===");
} |