From 6038a93ef9d8bd320d19ec98d6824729fa157a3e Mon Sep 17 00:00:00 2001 From: nullchinchilla Date: Sat, 4 May 2024 12:03:07 -0400 Subject: [PATCH] Optimize load updating logic by batching CPU and speed calculations in a loop --- binaries/geph5-exit/src/ratelimit.rs | 45 ++++++++++++++-------------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/binaries/geph5-exit/src/ratelimit.rs b/binaries/geph5-exit/src/ratelimit.rs index 3aae183..bebb588 100644 --- a/binaries/geph5-exit/src/ratelimit.rs +++ b/binaries/geph5-exit/src/ratelimit.rs @@ -50,29 +50,30 @@ pub fn update_load_loop() { let mut last_byte_count = 0; let mut last_speed = 0.0; loop { - sys.refresh_all(); - let cpu_usage: f32 = sys - .cpus() - .iter() - .map(|cpu| cpu.cpu_usage()) - .max_by_key(|s| (s * 1000.0) as u32 / 1000) - .unwrap_or(0.0) - / 100.0; - cpu_accum = cpu_accum * 0.99 + cpu_usage * 0.01; - - CPU_USAGE.store(cpu_accum, Ordering::Relaxed); - let new_byte_count = TOTAL_BYTE_COUNT.load(Ordering::Relaxed); - let byte_diff = new_byte_count - last_byte_count; - let byte_rate = byte_diff as f32 / last_count_time.elapsed().as_secs_f32(); - last_speed = last_speed * 0.99 + byte_rate * 0.01; // Exponential decay for current speed - CURRENT_SPEED.store(last_speed, Ordering::Relaxed); - - last_count_time = Instant::now(); - last_byte_count = new_byte_count; - + for _ in 0..100 { + sys.refresh_all(); + let cpu_usage: f32 = sys + .cpus() + .iter() + .map(|cpu| cpu.cpu_usage()) + .max_by_key(|s| (s * 1000.0) as u32 / 1000) + .unwrap_or(0.0) + / 100.0; + cpu_accum = cpu_accum * 0.99 + cpu_usage * 0.01; + + CPU_USAGE.store(cpu_accum, Ordering::Relaxed); + let new_byte_count = TOTAL_BYTE_COUNT.load(Ordering::Relaxed); + let byte_diff = new_byte_count - last_byte_count; + let byte_rate = byte_diff as f32 / last_count_time.elapsed().as_secs_f32(); + last_speed = last_speed * 0.99 + byte_rate * 0.01; // Exponential decay for current speed + CURRENT_SPEED.store(last_speed, Ordering::Relaxed); + + last_count_time = Instant::now(); + last_byte_count = new_byte_count; + + std::thread::sleep(Duration::from_millis(100)); + } tracing::info!(load = get_load(), "updated load"); - - std::thread::sleep(Duration::from_millis(100)); } }